gpt4 book ai didi

javascript - 如何在 JS 中从 ArrayBuffer 写入文件

转载 作者:IT老高 更新时间:2023-10-28 23:07:11 30 4
gpt4 key购买 nike

我正在尝试为 Meteor 框架编写文件 uploader 。原理是将客户端上的文件从ArrayBuffer中拆分成4096位的小包,通过Meteor.method发送到服务器。

下面的简化代码是客户端向服务器发送 block 的部分,它会重复直到offset达到data.byteLength :

// data is an ArrayBuffer
var total = data.byteLength;
var offset = 0;

var upload = function() {
var length = 4096; // chunk size

// adjust the last chunk size
if (offset + length > total) {
length = total - offset;
}

// I am using Uint8Array to create the chunk
// because it can be passed to the Meteor.method natively
var chunk = new Uint8Array(data, offset, length);

if (offset < total) {
// Send the chunk to the server and tell it what file to append to
Meteor.call('uploadFileData', fileId, chunk, function (err, length) {
if (!err) {
offset += length;
upload();
}
}
}
};
upload(); // start uploading

下面的简化代码是服务器上接收 block 并将其写入文件系统的部分:

var fs = Npm.require('fs');
var Future = Npm.require('fibers/future');

Meteor.methods({
uploadFileData: function(fileId, chunk) {
var fut = new Future();
var path = '/uploads/' + fileId;

// I tried that with no success
chunk = String.fromCharCode.apply(null, chunk);

// how to write the chunk that is an Uint8Array to the disk ?
fs.appendFile(path, chunk, 'binary', function (err) {
if (err) {
fut.throw(err);
} else {
fut.return(chunk.length);
}
});
return fut.wait();
}
});

我未能将有效文件写入磁盘,实际上文件已保存但我无法打开它,当我在文本编辑器中看到内容时,它类似于原始文件(例如 jpg)但有些字符不同,我认为这可能是编码问题,因为文件大小不一样,但我不知道如何解决...

最佳答案

保存文件就像使用 Uint8Array 对象创建一个新的缓冲区一样简单:

// chunk is the Uint8Array object
fs.appendFile(path, Buffer.from(chunk), function (err) {
if (err) {
fut.throw(err);
} else {
fut.return(chunk.length);
}
});

关于javascript - 如何在 JS 中从 ArrayBuffer 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31581254/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com