微信小程式開發(三)
阿新 • • 發佈:2019-02-19
上傳照片到快取
這裡實現上傳本地照片/拍攝照片並上傳顯示到當前頁面的功能,主要對JS檔案分析
STEP1實現選擇本地相簿/拍攝功能
wxml內繫結choosWay
函式:
<image class="upload-picture" wx:if="{{!uploadSuc}}" mode="widthFix" src='../../img/upload.jpg' bindtap='chooseWay'></image>
chooseWay
函式實現:
// 彈窗顯示照片提交方式
chooseWay: function() {
let that = this ;
wx.showActionSheet({ // 引入彈窗
itemList: ['從相簿中選擇','拍照'],
itemColor:"#f7982a",
success: function(res) {
// 根據彈窗中對應的選項返回呼叫wx.chooseImage時所需要的型別
if (!res.cancel) {
if(res.tapIndex==0) {
that.chooseWxImage('album') //從相簿中選擇
} else if(res.tapIndex==1 ) {
that.chooseWxImage('camera') // 拍攝
}
}
}
})
},
STEP2獲取照片
//獲取照片
chooseWxImage:function(type) {
let that = this;
wx.chooseImage({
sizeType: ['original', 'compressed'],
sourceType: [type],
success: function (res) {
// 此時可以通過下面的方式獲取到上傳的照片的路徑
var tempFilePaths = res.tempFilePaths;
// 設定當前的圖片路徑
that.setData({
img_path: res.tempFilePaths[0],
uploadSuc: true,
})
},
})
},
這裡要特別注意,如果需要在wx.chooseImage
(或其他微信小程式介面函式內)對this.data
資料進行更改時,需要在該函式外let that = this
。這與JS一樣,如果在介面內直接使用this,this指代的是當前藉口內的函式。
STEP3用wxml顯示圖片
<image class="upload-picture" wx:if="{{uploadSuc}}" mode="widthFix" src="{{img_path}}"></image>
實現結果: