javascript 文件类型转换的几种方式
Uint8Array
转ArrayBuffer
js
let uint8Array = new Uint8Array([1, 2, 3, 4, 5]);
let arrayBuffer = uint8Array.buffer;
console.log(arrayBuffer); // <ArrayBuffer 00 01 02 03 04 05>
ArrayBuffer
转Uint8Array
js
// 假设你有一个ArrayBuffer,我们将其称为buffer
let buffer = new ArrayBuffer(16);
// 创建一个Uint8Array对象,使用ArrayBuffer作为构造函数的参数
let uint8 = new Uint8Array(buffer);
console.log(uint8); // 输出Uint8Array对象
ArrayBuffer
转File
提示
Uint8Array and ArrayBuffer 可以直接传入 File 构造
js
let buffer = new ArrayBuffer(16);
let file = new File([buffer], "filename.bin", {
type: "application/octet-stream",
});
let uint8 = new Uint8Array([1]);
let file = new File([uint8], "filename.bin", {
type: "application/octet-stream",
});
js
// 假设你有一个ArrayBuffer,我们将其称为buffer
let buffer = new ArrayBuffer(16);
// 创建一个Blob对象,该对象包含buffer中的数据
let blob = new Blob([buffer], { type: "application/octet-stream" });
// 创建一个File对象,使用Blob作为构造函数的参数
let file = new File([blob], "filename.bin", {
type: "application/octet-stream",
});
console.log(file); // 输出File对象
File
转ArrayBuffer
使用Blob+Promise
js
var file = new File(["name"], "1.txt");
file
.slice(0, file.size)
.arrayBuffer()
.then((arrayBuffer) => {
console.log(arrayBuffer);
});
使用回调函数
js
let file = new File(["name"], "1.txt");
const fileReader = new FileReader();
// 定义文件加载完成后的处理函数
fileReader.onload = function (event) {
const arrayBuffer = event.target.result;
// 在这里你可以使用 arrayBuffer,例如将其发送到服务器或进行其他处理
console.log(arrayBuffer);
};
// 将文件读取为 ArrayBuffer
fileReader.readAsArrayBuffer(file);