一、wxml文件
頁面上寫上傳圖片的按鈕,按鈕綁定chooseImg。
<button bindtap="chooseImg" type="primary" class="uploadImg">上傳單張圖片</button> <view class="myImage"> <image src="{{imageUrl}}"></image> </view>
二、wxss文件
.myImage{ margin: 30rpx auto; text-align: center; } image{ width: 420rpx; height: 300rpx; } .uploadImg{ margin: 30rpx; }
三、js文件
1 Page({ 2 //第一步:選擇要上傳的圖片 3 chooseImg(){ 4 let that = this 5 wx.chooseImage({ 6 count: 1, 7 sizeType: ['original', 'compressed'], 8 sourceType: ['album', 'camera'], 9 success (res) { 10 console.log("選擇成功",res); 11 wx.showLoading({ 12 title: '上傳中', 13 }) 14 // tempFilePath可以作為img標簽的src屬性顯示圖片 15 const tempFilePaths = res.tempFilePaths 16 17 //調用uploadImg(tempFile)函數,實現圖片上傳功能 18 that.uploadImg(tempFilePaths[0]) 19 } 20 }) 21 }, 22 //第二步:上傳所選圖片到雲存儲 23 uploadImg(tempFile){ 24 console.log("要上傳圖片的臨時路徑",tempFile) 25 let timestamp = (new Date()).valueOf() 26 wx.cloud.uploadFile({ 27 cloudPath: +timestamp+'.png', //雲存儲的路徑,開發者自定義 28 filePath: tempFile, // 文件路徑 29 }).then(res => { 30 console.log("上傳成功",res) 31 wx.showToast({ 32 title: '上傳成功', 33 icon:"success", 34 duration:2000 35 }) 36 let that = this 37 setTimeout(function(){ 38 that.setData({ 39 imageUrl: res.fileID 40 }) 41 },2000) 42 }) 43 .catch(err => { 44 console.log("上傳失敗",err); 45 }) 46 } 47 })
四、界面展示