我需要将 File 对象传递给跨域 iframe,以便可以使用 XHR 上传。我使用easyXDM进行跨域通信,但相关的一点是浏览器如何处理传递这个对象。
fileUpload: function (data, success, error) {
var file = data.file,
name = data.name,
size = data.size,
params = data.params;
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
if (e.lengthComputable)
console.log(e.loaded);
}
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4)
success();
}
params = params || {};
params['qqfile'] = name;
var queryString = qq.obj2url(params, '/api/2/photo/upload');
xhr.open("POST", queryString, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(file);
}
通过 postMessage api 传递数据后调用上述方法;当它到达这里时,文件对象,它曾经看起来像这样(从 Web Inspector 打印):
File
lastModifiedDate: Mon Jul 13 2009 23:32:31 GMT-0600 (Mountain Daylight Time)
name: "Chrysanthemum.jpg"
size: 879394
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
现在只是一个普通对象,没有文件:
Object
lastModifiedDate: "2009-07-14T05:32:31.000Z"
name: "Chrysanthemum.jpg"
size: 879394
type: "image/jpeg"
webkitRelativePath: ""
__proto__: Object
因此,在文件引用丢失的情况下,Xhr 在上传时不会传递任何二进制数据。如何成功地将 File 对象传递给 iframe?