小程序文件base64转file类型

const base64ToFile = (base64data) => {
  return new Promise(async (resolve) => {
    if (String(base64data).includes('base64')) {
      const fsm = wx.getFileSystemManager();
      const FILE_BASE_NAME = 'tmp_base64src'; //自定义文件名
      const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
      if (!format) {
        return (new Error('ERROR_BASE64SRC_PARSE'));
      }
      const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
      const buffer = wx.base64ToArrayBuffer(bodyData);
      fsm.writeFile({
        filePath,
        data: buffer,
        encoding: 'binary',
        success() {
          console.log('文件地址', filePath)
          resolve(filePath)
        },
        fail() {
          resolve(new Error('ERROR_BASE64SRC_WRITE'));
        }
      })
    } else {
      resolve(base64data)
    }
  })
}

await base64ToFile(url).then((url) => {console.log(url)})

你可能感兴趣的:(微信小程序,小程序,前端,javascript)