钉钉小程序上传文件到七牛云或阿里云(OSS)实现

共有代码

function getTimestamp() {
  return new Date().getTime() / 1000;
}
dd.chooseImage({
      sourceType: ['camera', 'album'],
      count: 3,
      success: (res) => {
        (res.filePaths || res.apFilePaths || []).forEach(path => {
          uploadFile(path);
        });
      },
      fail: (res) => {
        if (res.error != 11) {
          dd.showToast({content: 'fail'});
        }
      }
}); 
  • 1、上传到阿里云

 function uploadFile(path) {
      if (!path) return;
      const hashCode = hash
        .sha1()
        .update(`${getTimestamp() + Math.random()}`)
        .digest('hex');
      const fileName = `${hashCode}${/\.[^\.]+$/.exec(filePath)[0]}`;
      const name = filePath.match(/\/([^/]*)$/)[1];
      const key = `attachments/${moment().format('YYYYMMDD')}/${fileName}`;
      const { fileToken: { accessKeyId, policy, securityToken, signature, expire } } = app.globalData;
      const formData = {
        name, key, policy,
        OSSAccessKeyId: accessKeyId,
        Signature: signature,
        'x-oss-security-token': securityToken,
        success_action_status: '200',
      };

      dd.uploadFile({
        url: config.fileHost, // 替换自己的阿里云地址
        fileType: 'image',
        fileName: 'file',
        filePath: filePath,
        formData: formData,
        success: (res) => {
          console.log(res, { key: formData.key, name: name });
        },
        fail: (err) => {
          dd.showToast({ content: '上传失败,稍后再试!' });
        },
        complete: (res) => {
          dd.hideLoading();
        }
      });
}
  • 2、上传到七牛云

function uploadFile(path) {
  if (!path) return;

  const hashCode = hash
    .sha1()
    .update(`${getTimestamp() + Math.random()}`)
    .digest('hex');
  const fileName = `${hashCode}${/\.[^\.]+$/.exec(filePath)[0]}`;
  const key = `attachments/${moment().format('YYYYMMDD')}/${fileName}`;
  const { token } = app.globalData;
  const formData = {
    token, key
  };

  dd.uploadFile({
    url: 'https://upload-z2.qiniup.com',
    fileType: 'image',
    fileName: 'file',
    filePath: filePath,
    formData: formData,
    success: (res) => {
      console.log(res.data);
    },
    fail: (err) => {
      dd.showToast({
        type: 'fail',
        content: '上传失败,稍后再试!'
      });
    },
    complete:
      (res) => {
        dd.hideLoading();
      }
  });
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容