在javascript中发布跨域的二进制数据 [英] Post binary data cross domain in javascript

查看:31
本文介绍了在javascript中发布跨域的二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Chrome 浏览器扩展程序,它获取当前选项卡视图的快照并将其上传到我无法控制的 Web 服务 API.Chrome 扩展库有一个函数 (chrome.tabs.captureVisibleTab.见 http://code.google.com/chrome/extensions/tabs.html) 获取快照并在数据 url 中返回数据.我对如何上传数据陷入僵局.

I'm writing a Chrome browser extension that takes a snapshot of the current tab's view and uploads it to a web service API that I don't control. The Chrome extension library has a function (chrome.tabs.captureVisibleTab. see http://code.google.com/chrome/extensions/tabs.html) that takes a snapshot and returns the data in a data url. I'm at an impasse as to how to get that data uploaded.

我尝试编写自己的多部分表单请求并使用 ajax 请求来发布数据.但是,ajax 坚持使用 UTF-8 编码数据,而 API 坚持使用 8 位编码的二进制.我想也许使用像 http://malsup.com/jquery/form/ 这样的文件上传插件工作,但我似乎无法将来自 JS 变量的数据转换为上传者将采用的形式.

I've tried to write my own multipart-form request and use an ajax request to POST the data. But, ajax insists on UTF-8 encoding the data and the API insists on 8-bit encoded binary. I thought maybe using a file uploader plugin like http://malsup.com/jquery/form/ would work, but I can't seem to get the data from the JS variable into a form the uploader will take.

任何关于至少一条新调查途径的想法都将受到高度赞赏.

Any ideas for at least a new path of investigation would be highly appreciated.

推荐答案

事实证明您可以做到这一点.

Turns out that you can do this.

Chrome 有一种通过 XMLHTTPRequest 发送 blob 的方法.

Chrome has a way to send a blob via XMLHTTPRequest.

这是 Chromium 问题跟踪器中示例代码的链接:

Here's a link to example code from the Chromium issue tracker:

http://code.google.com/p/铬/问题/细节?id=35705#c34

XMLHttpRequest.prototype.sendAsBinary = function(datastr,contentType) {
    var bb = new BlobBuilder();
    var len = datastr.length;
    var data = new Uint8Array(len);
    for (var i=0; i<len; i++) {
            data[i] = datastr.charCodeAt(i);
    }
    bb.append(data.buffer);
    this.send(bb.getBlob(contentType));
}

这篇关于在javascript中发布跨域的二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆