Reading an uploaded file into memory using pure Javascript
You have a File
object in Javascript (e.g. from a drag & drop upload or a <input type="file">
) which you want to read into memory in the browser. You don’t want to use any library to do that but prefer a pure Javascript solution.
Solution
Use this function:
/**
* Utility function to read an entire file into memory.
*
* The handler function gets passed an array of objects:
* {
* name: filename as string,
* size: size in bytes as number,
* type: MIME type as string,
* content: file content as Uint8Array
* }
* @param file The file to read
* @param handler
*/
function readFileIntoMemory (file, callback) {
var reader = new FileReader();
reader.onload = function () {
callback({
name: file.name,
size: file.size,
type: file.type,
content: new Uint8Array(this.result)
});
};
reader.readAsArrayBuffer(file);
}
Usage example:
// Usage example
readFileIntoMemory(file, function(fileInfo) {
console.info("Read file " + fileInfo.name + " of size " + fileInfo.size);
// You can use fileInfo.content, which is a Uint8Array, here
});