Search code examples
javascriptmultipartform-datafetch-apiform-dataarraybuffer

Create multipart file upload from Uint8ClampedArray via fetch


I crafted a binary file in the Browser in JavaScript as Uint8ClampedArray and now need to upload it to a webserver as if it was chosen from a file-picker.

I tried this:

var data = new Uint8ClampedArray(32);
data[0] = 0x42;
data[1] = 0x4D;
postdata = new FormData();
postdata.append('data', new Blob(data), 'test.txt');
fetch('http://localhost/',{
    method: 'POST',
    body: postdata
});

But it creates this request:

POST / HTTP/1.1
content-length: 230
content-type: multipart/form-data; boundary=----WebKitFormBoundaryfsPRCG3QGnD2bWZS

------WebKitFormBoundaryfsPRCG3QGnD2bWZS
Content-Disposition: form-data; name="data"; filename="test.txt"
Content-Type: application/octet-stream

6677000000000000000000000000000000
------WebKitFormBoundaryfsPRCG3QGnD2bWZS--

And thus this Textfile :(

6677000000000000000000000000000000

How do I create a valid binary Blob()? Thx!


Solution

  • try this way,

    var data = new Uint8ClampedArray(32);
    data[0] = 0x42;
    data[1] = 0x4D;
    postdata = new FormData();
    
    // Blob constructor takes an Array. so you need provide `[data]` not `data`
    postdata.append('data', new Blob([data], {type: "text/plain"}), 'test.txt');
    
    fetch('http://localhost/',{
        method: 'POST',
        body: postdata
    });