How to write a file from an ArrayBuffer in JS

前端 未结 3 1313
花落未央
花落未央 2020-12-31 03:33

I am trying to write a file uploader for Meteor framework. The principle is to split the fileon the client from an ArrayBuffer in small packets of 4096 bits that are sent to

相关标签:
3条回答
  • 2020-12-31 04:11

    Saving the file was as easy as creating a new Buffer with the Uint8Array object :

    // chunk is the Uint8Array object
    fs.appendFile(path, Buffer.from(chunk), function (err) {
        if (err) {
          fut.throw(err);
        } else {
          fut.return(chunk.length);
        }
    });
    
    0 讨论(0)
  • 2020-12-31 04:25

    Building on Karl.S answer, this worked for me, outside of any framework:

    fs.appendFileSync(outfile, new Buffer(arrayBuffer));
    
    0 讨论(0)
  • 2020-12-31 04:30

    Just wanted to add that in newer Meteor you could avoid some callback hell with async/await. Await will also throw and push the error up to client

    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;
      }
    });
    
    0 讨论(0)
提交回复
热议问题