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

跟風遠走 提交于 2019-11-29 14:16:44

问题


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!


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/3743047/uploading-a-binary-string-in-webkit-chrome-using-xhr-equivalent-to-firefoxs-se

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!