Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading