上傳圖片的話就做上傳頭像的時候遇到了,就拿上傳頭像舉個例子吧
得知道我們都用到什么api,而且提醒一下,這個需要后端配合,因為最后需要上傳到服務(wù)器
先寫一下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{
//把圖片上傳到服務(wù)器
e.upload_file(a.tempFilePaths[0])
}
}
});
},
- 其三,把圖片上傳到服務(wù)器----
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
});
}
});
},