Search code examples
javascriptfilereader

How to convert the selected file to blob format?


I have simple input-file field.

<input  type="file"
       id="openselect"
       name="files[]"
       (change)="fileSelect($event)">

It has related function that tries to convert selected file to BLOB format.

openselect.addEventListener("change", fileSelect, false);
function fileSelect(event) {
  const file = event.target['files'][0];
  const fileReader = new FileReader();
  fileReader.readAsText(file);
  console.log(fileReader.result)    // null
  console.log('iamge as blob: ', new Blob([fileReader.result]))        // meta info
}

As a result, console only displays file meta info, but doesnt display BLOB-string.

Please help me convert selected file to a BLOB-string.

Here is a live example.


Solution

  • Take a look at Mozilla's FileReader Documentation (https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result):

    This example presents a function, read(), which reads a file from a file input. It works by creating a FileReader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read().

    Solution: Live Example

    Another Question that might help you HTML5 FileReader how to return result?