6

I want to send a multipart form using XMLHttpRequest. The file I want to attach is a jpg file. Appending the file to the FormData object works fine.

But I'd like to process the image file before sending it. Therefore I have a library that takes a Uint8Array as input and output as well. So I have the processed image as UInt8Array.

I tried to use

form.append("picture", new Blob(fileAsArray, {type: "image/jpg"} ));

but it creates an octet/stream. So how can I send the Uint8Array via XMLHttpRequest multipart/form so that the server sees the same as when sending the file object?

bebo
  • 819
  • 1
  • 9
  • 26
  • Convert it to base64 string with `var base64Data = btoa(String.fromCharCode.apply(null, yourArray));` – adeneo Feb 28 '15 at 21:38
  • Hm, that seems to be [just fine](https://developer.mozilla.org/en-US/docs/Web/API/FormData#append()). What browser are you using? – Bergi Feb 28 '15 at 21:40

2 Answers2

12

Notice that the Blob constructor takes an array of typed arrays (or other sources) as its parameter. Try

form.append("picture", new Blob([fileAsArray], {type: "image/jpg"} ));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Probably it isn't the direct response to the question, but I have created a function to upload an ArrayBuffer as a file using not XMLHttpRequest, but fetch.

So here is my version with Javascript Fetch:

function uploadArrayBufferRawImage(arraybuffer)
{
    var formData = new FormData();
    formData.append("image",
                     new Blob([arraybuffer], {type: "image/x-myrawformat-raw"}),
                     new Date().toJSON() + ".raw");
    fetch("scripts/store_image.php", {
        method: 'POST',
        body: formData
    }).then(function(resp)
    {
        return resp.json();
    }).then(function(json)
    {
        console.log(json);
    });
}
Fernando
  • 1,477
  • 2
  • 14
  • 33