Search code examples
javascriptblobcreate-react-app

create-react-app javascript convert file to a Uint8Array


I have a create-react-app that updates firmware of connected bluetooth devices.

In order to do this, I need to convert the firmware file (.zip) to a Uint8Array.

The firmware file is saved locally in my public/ folder

And so I try to extract these bytes by with this function:

var fimware_zip = process.env.PUBLIC_URL + '/ZioV8_1.2.7.zip'    
this.loadFile(fimware_zip)

With loadFile defined as:

  // Load a file, set the bytes to firmware_byte_array
  loadFile = async (my_file) => {

    console.log(my_file)
    var fr = new FileReader();

    fr.onload = (e) =>
    { 
      var arrayBuffer = e.target.result;
      var array = new Uint8Array(arrayBuffer);
      this.setState({ firmware_byte_array: array})
    }

    fr.readAsArrayBuffer(my_file);
  }

However I get the following error:

Unhandled Rejection (TypeError): Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'.

I've searched high and low looking how to convert a file into a Blob type and I just cant do it.

I've also tried putting the .zip file in the src/ folder and importing it in using

import fimware_zip from './ZioV8_1.2.7.zip'

But that also doesnt work

Any help would be greatly appreciated


Solution

  • You can only use readAsArrayBuffer on Blobs or File objects (such as those you get from input type="file" elements).

    I assume there's some kind of server process involved in this app, in which case you can use fetch:

    const loadFile = async (my_file) => {
        const response = await fetch(my_file);
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        }
        const array = new Uint8Array(await response.arrayBuffer());
        // ...use or return `array` here...
    };