本文介绍了使用 XHR 在 WebKit/Chrome 中上传二进制字符串(相当于 Firefox 的 sendAsBinary)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用多个尖端 WebKit 功能的 web 应用程序.它本质上是这样做的:使用 FileReader 读取本地文件,使用 JavaScript 解压缩库将每个文件解压缩为字符串,并使用 XMLHttpRequest 发布每个文件.这对文本文件很有用,但不幸的是它会破坏二进制文件(在这种情况下是图像).Firefox 有一个 sendAsBinary 方法可以解决这个问题,但它是非标准的,更重要的是,它不适用于我们依赖于其他功能的 WebKit/Chrome.

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:

  • 使用长字符串 (像这样).
  • 在 xhr 对象上设置一堆标题(as such)
  • 使用 BlobBuilder,将字符串附加到构建器,并使用 getBlob 获取要上传的 blob (建议在有关此的 Chrome 问题线程中)
  • 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!

推荐答案

我也遇到了同样的问题.

I had the same problem.

这个对我有用:

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

在这里查看:http://javascript0.org/wiki/Portable_sendAsBinary

这篇关于使用 XHR 在 WebKit/Chrome 中上传二进制字符串(相当于 Firefox 的 sendAsBinary)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 09:50