create-react-app javascript 将文件转换为 Uint8Array
create-react-app javascript convert file to a Uint8Array
我有一个 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/ 文件夹中并在 using
中导入它
import fimware_zip from './ZioV8_1.2.7.zip'
但这也行不通
如有任何帮助,我们将不胜感激
您只能对 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...
};
我有一个 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/ 文件夹中并在 using
中导入它import fimware_zip from './ZioV8_1.2.7.zip'
但这也行不通
如有任何帮助,我们将不胜感激
您只能对 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...
};