Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading a binary string in WebKit/Chrome using XHR (equivalent to Firefox's sendAsBinary)

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:

  • Mocking a file upload request with headers, boundaries, and so forth in a long string (like this).
  • Setting a bunch of headers on the xhr object (as such)
  • Using the 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!

like image 426
heydenberk Avatar asked Sep 18 '10 19:09

heydenberk


People also ask

How do I send a binary file?

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.

How is binary data passed in the postman?

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.

How does JavaScript handle binary data?

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.


2 Answers

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

like image 132
Sebastien Avatar answered Oct 23 '22 12:10

Sebastien


You can encode it with base64 and decode it on the server.

like image 1
jcubic Avatar answered Oct 23 '22 12:10

jcubic