我正在尝试为Meteor框架编写文件上传器。 其原理是在客户端将文件从ArrayBuffer中分割成小的4096位数据包,然后通过Meteor.method发送到服务器。
下面是客户端发送数据块到服务器的简化代码,直到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
以下是服务器端接收数据块并将其写入文件系统的简化代码:
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)类似,但有些字符不同,我认为这可能是编码问题,因为文件大小不一样,但我不知道如何解决...