簡體   English   中英

如何從JS中的ArrayBuffer寫入文件

[英]How to write a file from an ArrayBuffer in JS

我正在嘗試為 Meteor 框架編寫一個文件上傳器。 原理是將客戶端上的文件從 ArrayBuffer 拆分成 4096 位的小數據包,通過 Meteor.method 發送到服務器。

下面的簡化代碼是客戶端向服務器發送塊的部分,它會重復,直到偏移量達到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)相似,但有些字符不同,我認為這可能是編碼問題,因為文件大小不一樣,但我不知道如何解決...

保存文件就像使用 Uint8Array 對象創建一個新的 Buffer 一樣簡單:

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

基於Karl.S answer ,這對我有用,在任何框架之外:

fs.appendFileSync(outfile, new Buffer(arrayBuffer));

只是想在較新的 Meteor 中添加它,您可以通過async/await避免一些回調地獄。 Await 也會拋出錯誤並將錯誤推送給客戶端

Meteor.methods({
  uploadFileData: async function(file_id, chunk) {
    var path = 'somepath/' + file_id; // be careful with this, make sure to sanitize file_id
    await fs.appendFile(path, new Buffer(chunk));
    return chunk.length;
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM