doUpload(filePath) {
const that = this;
var timestamp = (new Date()).valueOf();
const cloudPath = timestamp + '.png';
wx.cloud.uploadFile({
cloudPath,
filePath
}).then(res => {
console.log('[上传文件] 成功:', res)
const {
params
} = that.data;
const {
imgUrl
} = params;
imgUrl.push(res.fileID);
params['imgUrl'] = imgUrl;
that.setData({
imgUrl,
});
}).catch(error => {
console.error('[上传文件] 失败:', error);
wx.showToast({
icon: 'none',
title: '上传失败',
duration: 1000
})
})
},
chooseImage: function () {
const that = this;
// 选择图片
wx.chooseImage({
count: 5,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
const filePath = res.tempFilePaths;
//将选择的图片上传
filePath.forEach((path, _index) => {
that.doUpload(path);
});
const {
tempFilePaths
} = that.data;
that.setData({
tempFilePaths: tempFilePaths.concat(filePath)
}, () => {
console.log(that.data.tempFilePaths)
})
},
fail: e => {
console.error(e)
}
})
},
小程序云开发上传多图时用时间戳给文件命名时会导致个别图片命名重复。
多图上传可能导致重复命名
- 初步解决方案如下:
filePath.forEach((path, _index) => {
// 上传之间加上不同延迟应该就行了
setTimeout(() => that.doUpload(path), _index);
});
但是这并不能完全解决问题!!!
会出现以下问题:
- 多图上传时命名还是会重复
- 这样也只是能解决单机上面的重复问题而已。如果两个用户同时操作,还是可能存在时间戳相同从而文件名相同的情况,图片可能会被覆盖。
以下为最终解决方案:
1、把用户标识加入到文件名中,也可以加入文件夹中,比如每个用户有自己的专属目录;
2、文件命名时加上随机数命名
const cloudPath = app.openid + '/' +
Math.floor(Math.random()*10000 + 10000) +'.png';