小程序云开发中上传多图时,使用时间戳为文件命名时会有重复命名,怎么解决这个问题?
发布于 5 年前 作者 cuili 13047 次浏览 来自 问答
 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'上传失败',
                        duration1000
                  })
            })
      },

      chooseImagefunction () {
            const that = this;
            // 选择图片
            wx.chooseImage({
                  count5,
                  sizeType: ['compressed'],
                  sourceType: ['album''camera'],
                  successfunction (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)
                        })
                  },
                  faile => {
                        console.error(e)
                  }
            })
      },
1 回复
filePath.forEach((path, _index) => {
    // 上传之间加上不同延迟应该就行了
  setTimeout(() => that.doUpload(path), _index);
});

不过这样也只是能解决单机上面的重复问题而已。如果两个用户同时操作,还是可能存在时间戳相同从而文件名相同的情况,图片可能会被覆盖,这是你的设计问题。两种方案:

  1. 把用户标识加入到文件路径中,比如每个用户有自己的专属目录;
  2. 用文件的特征信息(wx.getFileInfo)来命名文件,就算传重复了也不怕覆盖,反正图片是一样的。
回到顶部