微信小程序上传图片

var that = this;
wx.chooseImage({
count: 1, //最多可以选择的图片总数
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
//启动上传等待中...
wx.showLoading({
title: '图片上传中',
})
var len = tempFilePaths.length;
for (var i = 0; i < len; i++) {
wx.uploadFile({
url: app.globalData.url + '/routine/auth_api/upload?uid=' + app.globalData.uid,
filePath: tempFilePaths[i],
name: 'pics',
formData: {
'filename': 'pics'
},
header: {
"Content-Type": "multipart/form-data"
},
success: function (res) {
wx.hideLoading();
if(res.statusCode == 403){
wx.showToast({
title: res.data,
icon: 'none',
duration: 1500,
})
} else {
var data = JSON.parse(res.data);
data.data.url = app.globalData.url + data.data.url;
that.data.dataimg.push(data);
that.setData({
dataimg: that.data.dataimg
});
var len2 = that.data.dataimg.length;
if (len2 >= 8) {
that.setData({
hidden: true
});
}
}
},
fail: function (res) {
wx.showToast({
title: '上传图片失败',
icon: 'none',
duration: 2000
})
}
});
}
}
});
 
////图片转base64

wx.getFileSystemManager().readFile({
filePath: res.tempFilePaths[0], //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
console.log('data:image/png;base64,' + res.data)
}
})

原文地址:https://www.cnblogs.com/jyc226/p/10320512.html