The front end converts the base64 image into a file file

1. Convert base64 to file specific code

  // base64图片转file的方法(base64图片, 设置生成file的文件名)
  function base64ToFile(base64, fileName) {
    
    
      // 将base64按照 , 进行分割 将前缀  与后续内容分隔开
      let data = base64.split(',');
      // 利用正则表达式 从前缀中获取图片的类型信息(image/png、image/jpeg、image/webp等)
      let type = data[0].match(/:(.*?);/)[1];
      // 从图片的类型信息中 获取具体的文件格式后缀(png、jpeg、webp)
      let suffix = type.split('/')[1];
      // 使用atob()对base64数据进行解码  结果是一个文件数据流 以字符串的格式输出
      const bstr = window.atob(data[1]);
      // 获取解码结果字符串的长度
      let n = bstr.length
      // 根据解码结果字符串的长度创建一个等长的整形数字数组
      // 但在创建时 所有元素初始值都为 0
      const u8arr = new Uint8Array(n)
      // 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元
      while (n--) {
    
    
        // charCodeAt():获取给定索引处字符对应的 UTF-16 代码单元
        u8arr[n] = bstr.charCodeAt(n)
      }
      // 利用构造函数创建File文件对象
      // new File(bits, name, options)
      const file =  new File([u8arr], `${
      
      fileName}.${
      
      suffix}`, {
    
    
        type: type
      })
      // 将File文件对象返回给方法的调用者
      return file;
  }

// 调用方法 此时的base64是初始file转换的
const file = base64ToFile(base64,'base64转file生成的文件')
console.log('base64转回file的---',file);
// 将转换后获得的file文件显示在页面的img元素上
document.querySelector('#img').src = window.webkitURL.createObjectURL(file)
File conversion process:

insert image description here

2. Code analysis

​ This method involves many knowledge points. First, because the prefix information part of base64 and the file content part are ,connected by , data:image/***;base64(前缀信息),xxxxx(文件内容)so split()the method is used to divide the base64 and separate the prefix file information from the file content. After obtaining the file prefix information, we can use string.match()the method combined with regular expressions to obtain the file type information (image/png, image/jpeg, image/webp) and the specific format suffix ( , , ) from the prefix, pngand jpegsave webpthese Information, used when creating the file file.

​ Next, we need to process the content of the file, and use window.atob()the method to decode the base64 file data to obtain the original file data flow information, but output it in a string format. Then use to new Uint8Array(length)create an 8-bit unsigned integer number array with the same length as the file data stream string, and the initial value of all elements of the integer array created by this method is 0. Then whilereplace the elements in the integer array created just now with the UTF-16 code unit of the character at the corresponding position in the file data stream character string according to the index, and then obtain the UTF-16 code unit of the character at the position corresponding to the index of the string string.charCodeAt(index). Values ​​are 0~65535integer numbers between .

​ Finally, we File(bits, name, options)pass in the corresponding parameters through the constructor to create a new file object and return it to the caller of the method. So far, the conversion from base64 to file has been completed.

3、base64

​ A complete base64 image contains two parts of information, one part is the file prefix information, and the other part is the file content information, for example: data:image/***(表示文件的类型);base64(表示格式),xxxxx(表示文件内容). In the process of converting base64 to file, we only need to convert the file content information, but the file type attribute after conversion needs to be determined by the file prefix information.

The red line marked part is the file prefix information, and the rest is the file content:

insert image description here

4, window.atob()andwindow.btoa()

​methodwindow.btoa() can encode a binary string into a base64-encoded ASCII string. We can use this method to encode strings that may encounter communication problems, but there is one thing to note: this method cannot encode Chinese characters, but can only encode English letters, English symbols and numbers.

insert image description here

​The methodwindow.atob() can decode the base64-encoded string and window.btoa()restore the encoded data; it can also decode the bsae64 format file into the original file data stream information.

insert image description here

Note: window.atob() It is window.btoa()compatible with browsers above IE9.

If you want to realize the encoding and decoding processing of Chinese characters, you need to combine encodeURIComponent()and decodeURIComponent()methods:

Encoding process: Chinese characters —> first encodeURI —> then btoa encoding
and decoding process: first atob decoding —> then decodeURI —> Chinese characters

5、File()

​The methodFile(bits, name[, options]) is the constructor of the File object, with two required parameters and one optional parameter:

​ The first parameter bits(必填)indicates the content of the file, which can contain ArrayBuffer, ArrayBufferView, Blob, or DOMStringobjects Array, and any combination of these objects;

​ The second parameter name(必填)indicates the attribute of the created file object name, that is, the name of the file.

​ The third parameter is options(可选)an object format parameter, indicating the optional attributes of the file. There are two optional attributes: ① type: string data, indicating the type of the file (image/png, image/jpeg, image/webp etc.), the default value is "". lastModified: Numeric data, indicating the Unix timestamp of the last modification time of the file, the default value is Data.now().

6. Related documents

The front-end FileReader object realizes image file conversion to base64

Base64

atob()

Uint8Array

match()

chartCodeAt()

File()

Guess you like

Origin blog.csdn.net/weixin_45092437/article/details/129143346