微信小程序云存储图片上传及数据库保存方法
微信小程序云存储图片上传及数据库保存方法
本文介绍了如何使用微信小程序云存储功能上传图片,并将图片文件ID保存到云数据库中。代码示例展示了如何实现图片上传、文件ID保存和数据库操作。
实现images中的图片全部上传到云存储,可以在上传图片成功后,将成功的文件ID保存到一个数组中,在所有图片都上传成功后,将这个数组保存到数据库中。
以下是修改后的代码:
saveAndUpload: function() {
// 保存邮件编号和图片到数据库
const mailNumber = this.data.mailNumber;
const images = this.data.images;
// const describe = this.data.describe;
// Get the current date
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
// Create the file name using the current date
var fileName = 'myImage/' + year + '-' + month + '-' + day + '/' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000) + '.jpg'
// Array to store the uploaded file IDs
var uploadedFileIDs = [];
// Upload images to cloud storage
for (var i = 0; i < images.length; i++) {
wx.cloud.uploadFile({
cloudPath: fileName,
filePath: images[i],
success: function(res) {
console.log('Upload successful: ', res.fileID);
uploadedFileIDs.push(res.fileID);
if (uploadedFileIDs.length === images.length) {
// All images have been uploaded
// Upload data to cloud database collection
const db = wx.cloud.database();
const collection = db.collection('yddata');
collection.add({
data: {
mailNumber: mailNumber,
images: uploadedFileIDs,
// describe: describe,
// date: date
},
success: function(res) {
console.log('Data uploaded successfully: ', res);
},
fail: function(err) {
console.error('Data upload failed: ', err);
}
});
}
},
fail: function(err) {
console.error('Upload failed: ', err);
}
});
}
}
代码说明:
- 创建一个数组
uploadedFileIDs用于存储上传成功的文件ID。 - 在上传图片成功后,将文件ID添加到
uploadedFileIDs数组中。 - 当所有图片都上传成功后,即
uploadedFileIDs的长度等于images的长度时,将uploadedFileIDs数组保存到云数据库中。
注意:
- 代码中使用了
wx.cloud.uploadFile接口上传图片到云存储。 - 代码中使用了
wx.cloud.database接口操作云数据库。 - 代码中使用了
console.log和console.error打印调试信息。
通过以上代码,可以实现将 images 中的所有图片上传到云存储,并将上传成功的文件ID保存到云数据库中。
原文地址: https://www.cveoy.top/t/topic/pwQm 著作权归作者所有。请勿转载和采集!