data: {
// 页面初始数据
imageList: [],
},
1、通过for 循环
upLoadImage: function () {
var that = this;
wx.chooseMedia({
count: 9,
mediaType: ['image', 'video'],
sourceType: ['album', 'camera'],
maxDuration: 30,
camera: 'back',
success(res) {
const tempFiles = res.tempFiles;
// 初始化 imageList,如果之前为空的话
if (that.data.imageList.length === 0) {
that.setData({
imageList: tempFiles.map(file => ({
...file,
serverId: null,
serverUrl: null
}))
});
}
for (let i = 0; i < tempFiles.length; i++) {
const file = tempFiles[i];
wx.uploadFile({
url: 'url', // 替换为您的服务器上传接口地址
filePath: file.tempFilePath,
name: 'file', // 服务器通过这个字段接收文件
formData: {
//'user': 'someone' // 额外表单信息,根据需要填写
},
success: function (uploadRes) {
// 文件上传成功后的回调
console.log('上传成功', uploadRes);
try {
// 解析服务器返回的JSON数据
const serverResponse = JSON.parse(uploadRes.data);
// 从服务器响应中提取文件ID和URL
const fileID = serverResponse.data.fileID;
const fileUrl = serverResponse.data.url;
// 创建更新的文件对象
const updatedItem = {
...file,
serverId: fileID,
serverUrl: fileUrl
};
//这边获取了fileID 写入数据库了,不需要了,可以删除
// 更新 imageList
const updatedImageList = that.data.imageList.map((item, index) => {
return index === i ? updatedItem : item;
});
// 更新界面显示
that.setData({
imageList: updatedImageList
});
} catch (error) {
console.error('解析服务器响应失败', error);
}
},
fail: function (uploadError) {
// 文件上传失败后的回调
console.error('上传失败', uploadError);
}
});
}
},
fail(err) {
// 处理选择媒体失败的情况
console.error('选择媒体失败', err);
}
});
},
2、通过forEach 循环
upLoadImage1: function () {
var that = this;
wx.chooseMedia({
count: 9,
mediaType: ['image', 'video'],
sourceType: ['album', 'camera'],
maxDuration: 30,
camera: 'back',
success(res) {
const tempFiles = res.tempFiles;
// 初始化 imageList,如果之前为空的话
if (that.data.imageList.length === 0) {
that.setData({
imageList: tempFiles.map(file => ({
...file,
serverId: null,
serverUrl: null
}))
});
}
// 遍历临时文件数组,并上传每个文件
tempFiles.forEach(function (file, index) {
wx.uploadFile({
url: 'url', // 替换为您的服务器上传接口地址
filePath: file.tempFilePath,
name: 'file', // 服务器通过这个字段接收文件
formData: {
//'user': 'someone' // 额外表单信息,根据需要填写
},
success: function (uploadRes) {
// 文件上传成功后的回调
console.log('上传成功', uploadRes);
try {
// 解析服务器返回的JSON数据
const serverResponse = JSON.parse(uploadRes.data);
// 从服务器响应中提取文件ID和URL
const fileID = serverResponse.data.fileID;
const fileUrl = serverResponse.data.url;
// 创建更新的文件对象
const updatedItem = {
...file,
serverId: fileID,
serverUrl: fileUrl
};
// 更新 imageList,确保只有当前文件被更新
const updatedImageList = that.data.imageList.map(item => {
return item.tempFilePath === file.tempFilePath ? updatedItem : item;
});
// 更新界面显示
that.setData({
imageList: updatedImageList
});
} catch (error) {
console.error('解析服务器响应失败', error);
}
},
fail: function (uploadError) {
// 文件上传失败后的回调
console.error('上传失败', uploadError);
}
});
});
},
fail(err) {
// 处理选择媒体失败的情况
console.error('选择媒体失败', err);
}
});
},