Reading a File and Getting its Binary Data in Javascript

Published on January 9, 2020

The binary data of a local file selected by the user can be retrieved using the readAsBinaryString() method of a FileReader object.

Example — Reading a Local File

Binary Data

HTML

<input type="file" id="file" />
<button id="read-file">Read File</button>

Javascript

document.querySelector("#read-file").addEventListener('click', function() {
	// no file selected to read
	if(document.querySelector("#file").value == '') {
		console.log('No file selected');
		return;
	}

	var file = document.querySelector("#file").files[0];

	var reader = new FileReader();
	reader.onload = function(e) {
		// binary data
		console.log(e.target.result);
	};
	reader.onerror = function(e) {
		// error occurred
		console.log('Error : ' + e.type);
	};
	reader.readAsBinaryString(file);
});

readAsBinaryString()

The readAsBinaryString method of a FileReader object asynchronously reads the file. The load event is fired once reading is finished and raw binary data is available.

How to Read Local Files with Javascript
Loading Comments