5

In my app, i'm uploading a file using FileReader and parsing it as an ArrayBuffer. The file properties are saved in an object, with structure like this:

file: {
    name: 'fileName', // type string
    content: ArrayBuffer // read like  FileReader.readAsArrayBuffer(uploadedFile)
}

When I want to save the file to backend, I'm using axios, and sending a request like this:

axios({
    url: "/api/v3/synchronous/commands",
    method: "POST",
    data: JSON.stringify(file),
    headers,
})

The problem is that when it get's stringifed, content inside file becomes an empty object {}. How to go about this issue, without having to convert ArrayBuffer to something else, and then converting it back to ArrayBuffer?

idjuradj
  • 1,355
  • 6
  • 19
  • 31
  • 1
    You can't really. "*The `ArrayBuffer` doesn't work, how can I fix it without changing the `ArrayBuffer`?*" :-P – Bergi Dec 22 '18 at 21:54
  • I'd suggest [constructing an actual `File`](https://developer.mozilla.org/en-US/docs/Web/API/File/File) – Bergi Dec 22 '18 at 21:55
  • That's not an option for now. Currently, it has to be done like this, because there are some more custom manipulations, not related to this, that I have to do. I tried this method, but it doesn't seem to work: https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String – idjuradj Dec 22 '18 at 22:10
  • 3
    If you are open to conversions, the simplest would be `JSON.stringify(Array.from(new Uint32Array(buffer)))` – Bergi Dec 22 '18 at 22:14
  • I'm open to conversions if I can't avoid them, and it seems I can't. I'm not sure I quote understand what does this piece of code do - does it convert from string to arraybuffer or the other way around? – idjuradj Dec 22 '18 at 23:42
  • It converts from a buffer to an array, so that you can JSON.stringify it. The reverse process, after `JSON.parse`ing it, would be `Uint32Array.from(array).buffer` – Bergi Dec 23 '18 at 10:36

0 Answers0