create-react-app javascript 将文件转换为 Uint8Array
Posted
技术标签:
【中文标题】create-react-app javascript 将文件转换为 Uint8Array【英文标题】:create-react-app javascript convert file to a 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'
但这也行不通
任何帮助将不胜感激
【问题讨论】:
【参考方案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...
;
【讨论】:
以上是关于create-react-app javascript 将文件转换为 Uint8Array的主要内容,如果未能解决你的问题,请参考以下文章
使用 create-react-app 脚手架搭建 react 项目,释放配置文件且注入 less 依赖
sh 用于将工作证书链接到create-react-app的脚本。允许您使用create-react-app和有效的SSL证书。
create-react-app:如何使用 https 而不是 http?