srv
srv

Reputation: 440

Javascript download multiple files and concatenate into a single file

I am supporting a website development work. Two binary files are downloaded to client browser upon request. The two files can come from two different sources.

The requirement is to concatenate both the files into a single file. Creating a single file in JavaScript and writing first downloaded content followed by second downloaded content is also acceptable.

Is this doable in JavaScript using FileAPI or any other related APIs?

Do I need to explore Chrome/Firefox Extension to achieve the same?

Upvotes: 3

Views: 2330

Answers (1)

martriay
martriay

Reputation: 5742

I'm not sure what you're trying to do but if I understood correctly you can store your files into ArrayBuffers and then merge them:

/**
 * Creates a new Uint8Array based on two different ArrayBuffers
 *
 * @private
 * @param {ArrayBuffers} buffer1 The first buffer.
 * @param {ArrayBuffers} buffer2 The second buffer.
 * @return {ArrayBuffers} The new ArrayBuffer created out of the two.
 */
var _appendBuffer = function(buffer1, buffer2) {
  var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
  tmp.set(new Uint8Array(buffer1), 0);
  tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
  return tmp.buffer;
};

Source: https://gist.github.com/72lions/4528834

Here you can read more about ArrayBuffers and you definitely should check MDN's Sending and Receiving Binary Data

Upvotes: 3

Related Questions