天天看點

微信小程式雲開發-雲存儲-上傳單張照片到雲存儲并顯示到頁面上

一、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 })      

四、界面展示

微信小程式雲開發-雲存儲-上傳單張照片到雲存儲并顯示到頁面上
微信小程式雲開發-雲存儲-上傳單張照片到雲存儲并顯示到頁面上
微信小程式雲開發-雲存儲-上傳單張照片到雲存儲并顯示到頁面上
微信小程式雲開發-雲存儲-上傳單張照片到雲存儲并顯示到頁面上