首页 > 技术文章 > 微信小程序云开发-云存储-上传单张照片到云存储并显示到页面上

AnnLing 2021-07-16 16:32 原文

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

四、界面展示

   

 

推荐阅读