I'm working on a webapp that uses several cutting-edge WebKit features. It essentially does this: reads a local file with the FileReader
, unzips each file into a string using a JavaScript unzip library, and POSTs each file using XMLHttpRequest. This works great for text files, but unfortunately it corrupts binary files (in this case, images). Firefox has a sendAsBinary
method that solves this problem, but it is non-standard, and more to the point, it doesn't work on WebKit/Chrome which we depend on for other features.
There are a TON of workarounds, and so far none of them work for me:
BlobBuilder
, appending the string to the builder, and using getBlob
to get a blob to upload (as recommended in the Chrome issue thread about this)What I'm looking for, most of all, is a forward-compatible solution. Thanks!
To upload a binary file, create a multipart request with a part that contains the JSON request body required by the resource, and a part for each file you want to upload. Each file must have its own part. To upload binary data to multiple fields, add a part for each field. The part names must match the field names.
In Postman, create a new PUT request and include your newly created API call in the request. On the Body tab, and select binary. Select the file you would like to upload. Click Send.
Binary data in JavaScript is implemented in a non-standard way, compared to other languages. But when we sort things out, everything becomes fairly simple. The basic binary object is ArrayBuffer – a reference to a fixed-length contiguous memory area.
I had the same problem.
This one worked for me:
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
check here: http://javascript0.org/wiki/Portable_sendAsBinary
You can encode it with base64 and decode it on the server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With