微信小程序踩坑日记3——上传照片至服务器

0. 引言

  主要解决将小程序端获取的图片保存在服务器上。亲测可用的服务端脚本。

1. 获取照片

  通过wx.chooseImage()方法,获取到图片,使用wx.uploadFile()上传图片。

wx.chooseImage({
    count: 1,//照片数量
    sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
    sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
    success: res => {
        console.log("开始上传图片");
        wx.uploadFile({
            url: "https://xxxx/xx.php",
            header: {
                'content-type': 'multipart/form-data'
            },
            filePath: res.tempFilePaths[0],//小程序保存的临时路径
            name: 'test',
            success: function(res) {
                console.log(res)
                if (res) {
                    wx.showToast({
                        title: '上传成功!',
                        duration: 3000
                    });
                }
            }
        })
    }
})

2. 服务端PHP

<?php
    $imgname = $_FILES['test']['name'];
    $tmp = $_FILES['test']['tmp_name'];
    $filepath = 'photo/';//保存的路径,相对于当前文件
    if(move_uploaded_file($tmp,$filepath.$openid.".png")){
        echo "上传成功";
    }else{
        echo "上传失败";
        echo $_FILES['test']['error'];//返回错误代码
    }
?>
原文地址:https://www.cnblogs.com/Lu-Yuyang/p/11253142.html