Introduction to FileReader of JavaScript and examples of how native and uniapp convert files into base64 encoded strings

Posted by Dargrotek on Wed, 29 Dec 2021 11:41:38 +0100

Use the FileReader object to view the MDN official description for details click here .

Introduction to FileReader object

  • Method of FileReader object:
methodparameterbrief introductionexplain
FileReader.readAsBinaryString(blob)Blob or File object to be readRead file as binary encodingThe specified Blob or File object will be read. When the reading is completed, the readyState will become DONE and the load (EN US) event will be triggered. At the same time, the result attribute will contain the original binary format of the read File. This method has been removed from the FileAPI standard, please use FileReader Readasarraybuffer() instead.
FileReader.readAsArrayBuffer(blob)Blob or File object to be read.Used to replace FileReader Method of readasbinarystring (BLOB)Used to start reading the specified Blob or File content. When the read operation is completed, the readyState becomes DONE and the load (EN US) event is triggered. At the same time, the result attribute will contain an ArrayBuffer object to represent the data of the read File.
FileReader.abort()nothingInterrupt read operationThis method can cancel the reading operation of FileReader, and the readyState is DONE after triggering; no matter whether the reading is successful or failed, the method will not return the reading result, which is stored in the result property.
FileReader.readAsDataURL(blob)Blob or File object to be read.Read file as DataURL(base64)The specified Blob or File object is read. When the read operation is completed, the readyState will become DONE and the loaded (EN US) event will be triggered. At the same time, the result attribute will contain a string in data:URL format (base64 encoding) to represent the contents of the read File.
FileReader.readAsText(blob[, encoding])Blob: binary object blob or File type; Encoding: optional; encoding type of string type; the default is "utf-8"Read the file as text. The second parameter is the encoding method of the text. The default value is UTF-8Blob or File objects can be converted into content (string form) according to special encoding format; This method is asynchronous, that is, you can view the results only after the execution is completed. If you directly view the results, it will return undefined; That is, you must mount the onload or onloaded method under the instance to process the converted results; After the conversion is completed, the readyState parameter will be converted to done, that is, the completed state. The event mounted by event("load") will be triggered, and the FileReader in the can be obtained through the formal parameters returned by the event The result attribute gets the converted result
  • Related events (click the event name to view the example):
eventexplain
FileReader.onabortThis event is triggered when the read operation is interrupted.
FileReader.onerrorThis event is triggered when an error occurs in a read operation.
FileReader.onloadThis event is triggered when the read operation completes.
FileReader.onloadstartThis event is triggered at the beginning of a read operation.
FileReader.onloadendThis event is triggered at the end of the read operation (either successful or failed).
FileReader.onprogressThis event is triggered when the Blob is read.


The specific usage in native is as follows

// Create an input file to select form elements
var input = document.createElement('input');
input.type = 'file'; // File select the type of form element
input.id = 'file';
input.name = 'file';
// File select the style of the form element
input.style.cssText = `
	width: 70%;
	margin: 10px 0 10px 0;
`;
// Adds the created file selection form element to an element
let uploadDom = document.getElementById("upload");
uploadDom .appendChild(input);
// change event for file selection form element
input.onchange = e => {
	const file = e.target.files[0];
	this.urls = window.webkitURL.createObjectURL(file)
	if(file.size > (1024*1024 * 50)){
		alert('Do not exceed 50 for a single file M,Please upload again')
	}
	let fileFullName = file.name; // Full name of the document
	let fileName = file.name.split('.')[0]; // File name
	let fileType = file.name.split('.')[1]; // file type
	// Create a FileReader object
	var reader = new FileReader();
	reader.readAsDataURL(file);
	reader.onload = function(e){
		let byte_64 = reader.result.substring(reader.result.indexOf(',')+1);  // File byte stream string (base64 encoded)
	}
}


The specific usage in uniapp is as follows

uni.chooseFile({
	count: 1, //Default 9
	sizeType: ['original', 'compressed'], //You can specify whether to use the original or compressed image. Both are available by default
	success: chooseFile => {
		console.log('chooseFile', chooseFile);
		const tempFiles = chooseFile.tempFiles;
		var reader = new FileReader();
		reader.readAsDataURL(tempFiles[0]);
		reader.onload = e => {
			this.fileFullName = tempFiles[0].name; // Full name of the document
			this.byte_64 = e.target.result.split(';base64,')[1]; // File byte stream string (base64 encoded)
			this.fileName = tempFiles[0].name.split('.')[0]; // File name
			this.fileType = tempFiles[0].name.split('.')[1]; // file type
		};
	}
});

Note: the method of intercepting the byte stream encoding of base64 is used here. You can choose the method by yourself.


If there are deficiencies, I hope you can give me more advice! thank you!

Topics: Javascript Front-end Vue.js uni-app uniapp