上传图片的话就做上传头像的时候遇到了,就拿上传头像举个例子吧
得知道我们都用到什么api,而且提醒一下,这个需要后端配合,因为最后需要上传到服务器
先写一下wxml吧
<view class='box' bindtap='uploadHeadImg'>上传</view>
- 其一,我们得先提示菜单:[从相册中选择,拍照]----
wx.showActionSheet
uploadHeadImg: function() {
let a = this;
wx.showActionSheet({
itemList: [ "从相册中选择", "拍照" ],
itemColor: "#f7982a",
success: function(e) {
//album:相册 //camera拍照
e.cancel || (0 == e.tapIndex ? a.chooseWxImageShop("album") : 1 == e.tapIndex && a.chooseWxImageShop("camera"));
}
});
},
- 其二,选择照片或者拍照,返回临时路径----
wx.chooseImage
//a:选择的类型 //album:相册 //camera拍照
chooseWxImageShop: function(a) {
var e = this;
wx.chooseImage({
sizeType: [ "original", "compressed" ],
sourceType: [ a ],//类型
count:1,
success: function(a) {
if(a.tempFiles[0].size> 2097152){
wx.showModal({
title: "提示",
content: "选择的图片过大,请上传不超过2M的图片",
showCancel: !1,
success: function(a) {
a.confirm;
}
})
}else{
//把图片上传到服务器
e.upload_file(a.tempFilePaths[0])
}
}
});
},
- 其三,把图片上传到服务器----
wx.uploadFile
upload_file: function(e) {
wx.showLoading({
title: "上传中"
});
wx.uploadFile({
url:url,
filePath: e,//图片路径
name: "user_avatar",
formData: {
token: a.globalData.token,
user_avatar: "filePath"
},
header: {
"Content-Type": "multipart/form-data"
},
success: function(a) {
wx.hideLoading();
wx.showToast({
title: "上传成功",
icon: "success",
duration: 3000
});
},
fail: function(a) {
wx.hideLoading();
wx.showToast({
title: "上传失败",
icon: "none",
duration: 3000
});
}
});
},