Basic usage of File, FileReader, Base64, Blob and conversion between Buffer and ArrayBuffer

File file

(File) object to get the information of the file. In fact, the File object is a special type of Blob, and the properties and methods of the Blob are available for the File object. In js, generally through the input element, click on the File object returned after the upload file is successful;

Define an input of type file in the input tag
<input type="file" ref="upload" accept=".docx,.pdf">
  • type: the current input type file
  • ref: equivalent to the unique identifier of the current input
  • accept: Specify the format of the uploaded file word or pdf
Binding listener table import event
mounted(){
	this.$refs.upload.addEventListener('change', e => {
		this.readExcel(e);
	})
}
methods: {
    readExcel(e) {
	console.log(e)
	const file = e.target.files;
	console.log(file)
    },
}
The print result file is a FileList array, each element of this array is a File object, and an uploaded file corresponds to a File object:

image
image

The attribute of file: length, returns the number of files contained in file. It can be multiple because it is a FileList array
file method: item() method can also use the subscript of file to represent: file.item(0) can also be written as file[0]

FileReader

FileReader is an asynchronous API for reading files and extracting their content for further use. FileReader can read Blobs into different formats. The FileReader class can read the content of the file referred to by the file class instance. To get the base64 address of the file selected by the user, the FileReader class must be used.

Create an instance of the filereader class:

const fileFr = new FileReader();

Common properties:
error:表示在读取文件时发生的错误;
result:文件内容。该属性仅在读取操作完成后才有效,数据的格式取决于使用哪个方法来启动读取操作。
Common methods of the FileReader object:
readAsArrayBuffer() 读取file文件的内容,并作为arraybuffer格式得到结果。
readAsDataURL() 读取file文件并返回file文件的base64地址。
readAsBinaryString() 以二进制字符串的形式读取文件。
readAsText() 按照指定的charset字符集以文本文件的形式读取file文件的内容。
//----表格导入方法
    readExcel(e) {
      const file = e.target.files;
      const fr = new FileReader();
      fr.readAsArrayBuffer(file[0])
      fr.onload = (e) => {
        // 文件的ArrayBuffer结果
        const buffer = Buffer.from(e.target.result)
      }
    },
Events commonly used by FileReader objects:
abort:该事件在读取操作被中断时触发;
error:该事件在读取操作发生错误时触发;
load:该事件在读取操作完成时触发;
progress:该事件在读取 Blob 时触发。
loadstart:开始读取文件时触发。
progress:读取文件过程中触发。

Base64

Base64 is a representation method for binary data based on 64 printable characters. Images can be converted to base64, HTTP requests can be reduced and strings can be decoded and encoded.

Decode and encode a base64 string:
atob():解码,解码一个 Base64 字符串;
btoa():编码,从一个字符串或者二进制数据编码一个 Base64 字符串。

Conversion between different formats:

1. File object to Base64:
const file = e.target.files;
const fr = new FileReader();
fr.readAsDataURL(file[0])
fr.onload = (e) => {
	console.log(e.target.result)
}
2. ArrayBuffer to blob
const blob = new Blob([new Uint8Array(buffer, byteOffset, length)]);
3. ArrayBuffer to base64
const base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
4. base64 to blob
const base64toBlob = (base64Data, contentType, sliceSize) => {
  const byteCharacters = atob(base64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}
5. Blob to ArrayBuffer
function blobToArrayBuffer(blob) { 
  return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = () => reject;
      reader.readAsArrayBuffer(blob);
  });
}
6. blob to base64
function blobToBase64(blob) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}
7. Blob to Object URL
const objectUrl = URL.createObjectURL(blob);
8. Convert blob to text
async() => {
	return await (new Response(blob).text())
}
9. Buffer to JSON
let bufferDatas = Buffer.from('woshibufferwenjian')
console.log(bufferDatas)
let json = JSON.stringify(bufferDatas, null, 2)
console.log(json)
10. JSON to Buffer
let bufferFile = Buffer.from(JSON.parse(json).data)
console.log(bufferFile)
11. Buffer to UTF-8 string
bufferFile.toString('utf8')

Guess you like

Origin blog.csdn.net/weixin_48138187/article/details/128951935