微信小程序云开发之云存储(实现图片上传和下载)


前言

我们经常将文件(音频、图片、压缩包、文档)存储在网上,我们的云开发平台为开发者提供“云存储”空间,开发者只需将文件上传,就可以得到这个文件的下载地址和File ID。

在这里插入图片描述

一、云存储的使用

代码如下(示例):

 wx.cloud.uploadFile({
        cloudPath:`上传的位置/$文件的命名`,
        filePath:临时文件路径,
        success(res){
        	//成功后的回调
        },
        fail(res){
			//失败后的回调
		}
      })

二、使用演练

1.上传图片到云存储中

效果:
在这里插入图片描述

wxml示例:

<view class="group">
    <text>附加图片:</text>
    <view class="img">
      <view class="img_row">
        <block wx:for="{{cloudImages}}" wx:key="index">
          <image class="img01" src="{{item}}"></image>
        </block>
      </view>
      <image class="img01" src="../../static/camera.png" bindtap="imgFile"></image>
    </view>
  </view>

js代码示例:

 imgFile(){
    var that=this
    wx.chooseImage({
      count:2, //上传图片最多不超2张
      success(res){
        /* console.log(res) */
        for(var i=0;i<res.tempFilePaths.length;i++){
          wx.cloud.uploadFile({
            cloudPath:`actionInfo/${Math.random()}_${Date.now()}.${res.tempFilePaths[i].match(/\.(\w+)$/)[1]}`,
            filePath:res.tempFilePaths[i],
            success(res){
              /* console.log(res) */
              that.data.cloudImages.push(res.fileID)
              that.setData({
                cloudImages:that.data.cloudImages
              })
              /* console.log(that.data.cloudImages) */
            }
          })
        }
      }
    })
  },

2.下载并保存图片到手机

代码如下(示例):

downLoadImage(event){
    wx.cloud.downloadFile({
      fileID:event.currentTarget.dataset.id,
      success(res){
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(){
            wx.showToast({
              title: '保存成功',
            })
          }
        })
      }
    })
  },

tips:上边的链接下载地址时FileID,如果链接下载图片地址是url,则调用的API是:wx.downloadFile({url:})
wx.saveImageToPhotosAlbum:将图片保存到手机中


  • 5
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值