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


前言

我们经常将文件(音频、图片、压缩包、文档)存储在网上,我们的云开发平台为开发者提供“云存储”空间,开发者只需将文件上传,就可以得到这个文件的下载地址和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:将图片保存到手机中


猜你喜欢

转载自blog.csdn.net/weixin_52312427/article/details/128462260