// 在小程序前端代码中
wx.cloud.uploadFile({
cloudPath: 'images/my-image.jpg', // 云存储中的路径
filePath: '/local/path/to/your/image.jpg', // 本地文件路径
success: res => {
console.log('上传成功', res.fileID);
// 将 fileID 存储到数据库或其他地方
},
fail: err => {
console.error('上传失败', err);
}
});
在这个示例中,cloudPath 是文件在云存储中的路径,filePath 是本地文件的路径。成功上传后,res.fileID 包含了上传文件在云存储中的唯一标识。
在云开发中,你也可以使用云函数来实现服务端上传文件的逻辑。以下是一个云函数的示例:
// 云函数代码
const cloud = require('wx-server-sdk');
cloud.init();
exports.main = async (event, context) => {
try {
const result = await cloud.uploadFile({
cloudPath: 'images/my-image.jpg', // 云存储中的路径
fileContent: Buffer.from(event.fileContent, 'base64'), // 文件内容,以 base64 格式传递
});
return result.fileID;
} catch (err) {
console.error(err);
return err;
}
};
在这个示例中,通过将文件内容以 base64 格式传递给云函数,云函数可以将文件上传到云存储中,并返回文件在云存储中的唯一标识。需要注意的是,在实际应用中,请根据你的具体需求来适配代码。
转载请注明出处:http://www.zyzy.cn/article/detail/5899/微信小程序