【问题标题】:create-react-app javascript convert file to a Uint8Arraycreate-react-app javascript 将文件转换为 Uint8Array
【发布时间】:2020-07-03 02:42:02
【问题描述】:

我有一个 create-react-app 可以更新连接的蓝牙设备的固件。

为此,我需要将固件文件 (.zip) 转换为 Uint8Array。

固件文件本地保存在我的 public/ 文件夹中

所以我尝试使用这个函数来提取这些字节:

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

将loadFile定义为:

  // 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);
  }

但是我得到以下错误:

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

我已经搜索过如何将文件转换为 Blob 类型的高低搜索,但我无法做到。

我也尝试将 .zip 文件放在 src/ 文件夹中并使用导入它

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

但这也行不通

任何帮助将不胜感激

【问题讨论】:

    标签: javascript blob create-react-app


    【解决方案1】:

    您只能在 Blob 或文件对象(例如从 input type="file" 元素中获得的对象)上使用 readAsArrayBuffer

    我假设这个应用程序涉及某种服务器进程,在这种情况下你可以使用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...
    };
    

    【讨论】:

      猜你喜欢
      • 2021-07-13
      • 2020-01-25
      • 2018-02-19
      • 1970-01-01
      • 2017-02-04
      • 2022-08-23
      • 1970-01-01
      • 2021-07-18
      • 2021-05-03
      相关资源
      最近更新 更多