3

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?

srv
  • 433
  • 9
  • 26
  • What does "merge" mean? – Alexander O'Mara Aug 15 '16 at 19:08
  • Oops! better I will refer as concatenate. – srv Aug 15 '16 at 19:10
  • This doesn't make much sense to me. Two binary files you literally concatenate? How is the resulting file useful or readable? Did you mean put the files in an archive like a zip file? – Thomas Langston Aug 15 '16 at 19:16
  • Too avoid server load this has been done. The first file will be of few MBs and has user specific data, where as the remaining large file will be downloaded from a different server, say Amazon S3 like that. The user application installed has the capability to read and understand the file content. – srv Aug 15 '16 at 19:32

1 Answers1

3

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

martriay
  • 5,632
  • 3
  • 29
  • 39