一.要點
1.選取圖片
-
wx.chooseImage({
-
sizeType: [], // original 原圖,compressed 壓縮圖,默認二者都有
-
sourceType: [], // album 從相冊選圖,camera 使用相機,默認二者都有
-
success: function (res) {
-
console.log(res);
-
var array = res.tempFilePaths, //圖片的本地文件路徑列表
-
}
-
})
2.上傳圖片
-
wx.uploadFile({
-
url: '', //開發者服務器的 url
-
filePath: '', // 要上傳文件資源的路徑 String類型!!!
-
name: 'uploadFile', // 文件對應的 key ,(后臺接口規定的關于圖片的請求參數)
-
header: {
-
'content-type': 'multipart/form-data'
-
}, // 設置請求的 header
-
formData: { }, // HTTP 請求中其他額外的參數
-
success: function (res) {
-
},
-
fail: function (res) {
-
}
-
})
二.代碼示例
-
// 點擊上傳圖片
-
upShopLogo: function () {
-
var that = this;
-
wx.showActionSheet({
-
itemList: ['從相冊中選擇', '拍照'],
-
itemColor: "#f7982a",
-
success: function (res) {
-
if (!res.cancel) {
-
if (res.tapIndex == 0) {
-
that.chooseWxImageShop('album')
-
} else if (res.tapIndex == 1) {
-
that.chooseWxImageShop('camera')
-
}
-
}
-
}
-
})
-
},
-
chooseWxImageShop: function (type) {
-
var that = this;
-
wx.chooseImage({
-
sizeType: ['original', 'compressed'],
-
sourceType: [type],
-
success: function (res) {
-
-
/*上傳單張
-
that.data.orderDetail.shopImage = res.tempFilePaths[0],
-
that.upload_file(API_URL + 'shop/shopIcon', res.tempFilePaths[0])
-
*/
-
-
/*上傳多張(遍歷數組,一次傳一張)
-
for (var index in res.tempFilePaths) {
-
that.upload_file(API_URL + 'shop/shopImage', res.tempFilePaths[index])
-
}
-
*/
-
}
-
})
-
},
-
upload_file: function (url, filePath) {
-
var that = this;
-
wx.uploadFile({
-
url: url,
-
filePath: filePath,
-
name: 'uploadFile',
-
header: {
-
'content-type': 'multipart/form-data'
-
}, // 設置請求的 header
-
formData: { 'shopId': wx.getStorageSync('shopId') }, // HTTP 請求中其他額外的 form data
-
success: function (res) {
-
wx.showToast({
-
title: "圖片修改成功",
-
icon: 'success',
-
duration: 700
-
})
-
},
-
fail: function (res) {
-
}
-
})
-
},
|