前端base64转file

很多时候上传图片需要前端把base64转换为file文件流,以formdata的格式传给后端。这里提供转换方法,亲测有效。

    base64toFile (dataBase64, filename = 'file') {
      let arr = dataBase64.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]  //设置file文件流的type名称
      let suffix = mime.split('/')[1]  //设置file文件流的name名称
      const bstr = window.atob(arr[1]);
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },

这格方法对于有前缀data:image/jpg;base64的完整base64格式,如果没有前缀,直接转就行。

如果报错Failed to execute 'atob' on 'Window': The string to be decoded is not correc...类似于这样的信息的话,是中英文编码字符串字符有问题,直接转换改成这样的:

    base64toFile (dataBase64, filename = 'file') {
      let arr = dataBase64.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      const bstr = decodeURIComponent(escape(window.atob((arr[1]).replace(/-/g, "+").replace(/_/g, "/")))); //更改成这样就不会报错
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },

上一篇:bolb、bloburl、file、base64间的转换


下一篇:mybatis的Sql语句打印