7

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?

2
  • Convert it to base64 string with var base64Data = btoa(String.fromCharCode.apply(null, yourArray)); Commented Feb 28, 2015 at 21:38
  • Hm, that seems to be just fine. What browser are you using? Commented Feb 28, 2015 at 21:40

2 Answers 2

14

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"} ));
Sign up to request clarification or add additional context in comments.

Comments

2

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);
    });
}

1 Comment

No need for a non-existent image/x-myrawformat-raw, just use application/octet-stream, the mime-type for "arbitrary binary data" as outlined in RFC 2046. But if you know the image format, which they do, then use that (image/jpeg in this case).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.