欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

五十二、微信小程序云开发中的云存储

发布时间:2024/10/8 编程问答 43 豆豆
生活随笔 收集整理的这篇文章主要介绍了 五十二、微信小程序云开发中的云存储 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

@Author:Runsen

暑假很长,明年就是找工作的时候了。这个时候必须比之前还要拼命。

百翻无下,努力就是我的代言词。今天,正式进入云存储的学习。云存储这个概念在之前学习的时候没有注意到。

下面是官方文档链接

官方文档

文章目录

  • 上传图片
  • 展示图片
  • 下载图片

上传图片

首先,我去查看上传图片的API。

上传图片的官方文档

wx.chooseImage(Object object):从本地相册选择图片或使用相机拍照。

下面我在index.wxml中给定,上传图片的按钮

<button bindtap="onloadimage">上传图片</button>

然后在index.js中的实现onloadimage的方法,下图是官方的示例。

在小程序中的云开发上传图片的API接口,官方文档如下;https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/storage/uploadFile/client.uploadFile.html

展示图片

在这里定义了一个image的空列表,当点击按钮时,通过调用云函数中的login,然后将返回的data保存到云数据库中。

下载图片

对于下载图片,通过定义data-fileid绑定fileID,然后通过fileID: event.target.dataset.fileid拿到fileID,下面就是一个wx.cloud.downloadFile云函数下载图片的方法,具体查看官方文档

下面是全部代码

index.wxml代码

<button bindtap="onloadimage">上传图片</button> <button bindtap="getimage">展示图片</button> <block wx:for="{{image}}"><image src="{{item.fileID}}"></image><button size="mini" data-fileid="{{item.fileID}}" bindtap="downloadimage">下载图片</button> </block>

index.js代码

//index.js const app = getApp() const db = wx.cloud.database()Page({data: {image: []},onloadimage:function(){wx.chooseImage({count: 1,sizeType: ['original', 'compressed'],sourceType: ['album', 'camera'],success (res) {// tempFilePath可以作为img标签的src属性显示图片const tempFilePaths = res.tempFilePaths;console.log(tempFilePaths[0]);wx.cloud.uploadFile({cloudPath: new Date().getTime() + ".png",filePath: tempFilePaths[0], // 文件路径success: res => {// get resource IDconsole.log(res.fileID)db.collection("image").add({data:{fileID:res.fileID,}}).then(res=>{console.log(res)}).catch(err=>{console.log(err)})},fail: err => {// handle error}})},})},// 展示图片getimage:function(){wx.cloud.callFunction({name:"login",}).then(res=>{db.collection("image").where({_openid:res.result.openid}).get().then(res2=>{console.log(res2)this.setData({image: res2.data})})})},// 下载图片downloadimage:function(event){wx.cloud.downloadFile({fileID: event.target.dataset.fileid, // 文件 IDsuccess: res => {// 返回临时文件路径console.log(res.tempFilePath)// 保存图片到手机相册wx.saveImageToPhotosAlbum({filePath: res.tempFilePath,success(res){wx.showToast({title: '保存成功',})}})},fail: console.error})} })

上传图片

下载图片

总结

以上是生活随笔为你收集整理的五十二、微信小程序云开发中的云存储的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。