云开发为开发者提供了存储空间、将文件上传到云端存储空间内以及带权限的云端文件下载能力,开发者可以使用云开发控制台或使用 SDK 调用接口来使用存储功能。
云开发默认支持 CDN 加速,并提供免费 CDN 域名。
每一个上传到云开发的文件都有一个全网唯一的 fileID,使用 fileID 可以更加安全便捷的访问文件,例如私有权限的文件的访问链接的有效期是有限的,开发者可以选择使用 fileID 动态的换取可以访问的文件链接地址。
部分小程序的组件(如image、video、cover-image等),支持传入云文件的 fileID,具体支持的情况,请访问微信官方文档 - 小程序的组件支持文档。
wx.cloud.uploadFile({
cloudPath: 'test/ceshi.png', // 上传至云端的路径
filePath: '', // 小程序临时文件路径,一般通过wx.chooseImage获取
}).then((res) => {
console.log(res.fileID)// 返回文件 ID
});
const tcb = require("tcb-js-sdk")//引入sdk——web
tcb.init({env: 'hj-id'})//初始化
app.uploadFile({
cloudPath: 'test/ceshi.png', // 上传至云端的路径
filePath: document.getElementById('file').files[0]//上传的文件
}).then((res) => {
console.log(res.fileID)// 返回文件 ID
});
const cloud= require('wx-server-sdk')//引入sdk——服务器端(有三种,看情况引入)
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV// API 调用都保持和云函数当前所在环境一致
});
cloud.uploadFile({
cloudPath: 'test/ceshi.png', // 上传至云端的路径
fileContent: fs.createReadStream('a/test.jpg')//文件流
}).then((res) => {
console.log(res.fileID)// 返回文件 ID
});
[这里是tcb对象(wx.cloud或tcb或cloud)].getTempFileURL({
fileList: [//要下载的文件 ID 组成的数组
'cloud://a/b/c',
'cloud://d/e/f'
]
}).then((res) => {
// fileList 是一个有如下结构的对象数组
// [{
// fileID: 'cloud://webte328c3-1251059088/腾讯云.png', // 文件 ID
// tempFileURL: '', // 临时文件网络链接
// maxAge: 120 * 60 * 1000, // 有效期
// }]
console.log(res.fileList)
});
[这里是tcb对象(wx.cloud或cloud)].downloadFile({
fileID: "cloud://a/b/c", // 文件 ID
}).then((res) => {
console.log(res.tempFilePath) // 小程序返回临时文件路径(已经下载到临时文件)
console.log(res.fileContent) // 云函数返回Buffer文件流类型
});
[这里是tcb对象(wx.cloud或tcb或cloud)].deleteFile({
fileList: [//要删除的文件 ID 组成的数组
'cloud://a/b/c',
'cloud://d/e/f'
]
}).then((res) => {
console.log(res.fileList)
});
如需设置文件权限,选择【权限设置】,根据实际需求,勾选存储桶权限并保存。
云储存说实话,我暂时还没找到什么太大的槽点,推荐,就酱。