0

I'm written a bit of AJAX that gets a file client side so that I can post it back to the server. The objected is fetched as an ArrayBuffer. However, upon posting this binary back to the server for saving, I need to include some metadata with this file. I've tried wrapping the ArrayBuffer with other strings in and object, but when I inspect the data server side, it appears to have only transferred the length of the ArrayBuffer.

I've tried converting the ArrayBuffer to a string via this answer:

https://stackoverflow.com/a/11058858/449511.

However, my ArrayBuffer's bytelength is 519843, which causes the exception:

Uncaught RangeError: ArrayBuffer length minus the byteOffset is not a multiple of the element size.

My understanding of ArrayBuffers is sparse, I've read MDN docs but can't find much else. I'm thankful for any further resources or ideas on how I can either convert this ArrayBuffer to a string or wrap my ArrayBuffer into an object.

Here is a snippet of my AJAX code:

$.ajax({
  type: 'POST',
  url:  'http://localhost:5000/',
  data: {fname: f, url:u, binary:b},  // the binary is an ArrayBuffer
});
Community
  • 1
  • 1
user449511
  • 249
  • 6
  • 14

1 Answers1

0

Just so it's documented, thanks @Markus in the comments. Using UInt8Array works. Also I just found this question to document exactly what I needed: Getting BLOB data from XHR request.

Using the ArrayBuffer to String answer linked in my question doesn't work well for large file sizes, so I wrote an iterative version and converted to base64 before posting in an object.

var binary_string = ''
bytes = new Uint8Array(ArrayBuffer object from ajax get);
for (var i = 0; i < bytes.byteLength; i++) {
    binary_string += String.fromCharCode(bytes[i]);
}
base64_string = window.btoa(binary_string);
Community
  • 1
  • 1
user449511
  • 249
  • 6
  • 14