使用jQuery的ajax方法来检索图像作为一个blob

我最近问了另一个(相关的)问题,导致了这个后续问题: 提交数据而不是input表单的文件

通过阅读jQuery.ajax()文档( http://api.jquery.com/jQuery.ajax/ ),似乎接受的数据types的列表不包括图像。

我试图检索使用jQuery.get(或jQuery.ajax,如果我必须)的图像,将此图像存储在Blob中,并将其上传到另一台服务器的POST请求。 目前,它看起来像是由于数据types不匹配,我的图像最终被破坏(字节大小不匹配等)。

执行这个代码如下(这是在咖啡脚本,但不应该很难parsing):

handler = (data,status) -> fd = new FormData fd.append("file", new Blob([data], { "type" : "image/png" })) jQuery.ajax { url: target_url, data: fd, processData: false, contentType: "multipart/form-data", type: "POST", complete: (xhr,status) -> console.log xhr.status console.log xhr.statusCode console.log xhr.responseText } jQuery.get(image_source_url, null, handler) 

我怎样才能检索到这个图像作为一个blob呢?

你不能用jQuery ajax来完成这个工作,而用原生的XMLHttpRequest来完成。

 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (this.readyState == 4 && this.status == 200){ //this.response is what you're looking for handler(this.response); console.log(this.response, typeof this.response); var img = document.getElementById('img'); var url = window.URL || window.webkitURL; img.src = url.createObjectURL(this.response); } } xhr.open('GET', 'http://jsfiddle.net/img/logo.png'); xhr.responseType = 'blob'; xhr.send(); 

http://jsfiddle.net/mowglisanu/9xY46/58/show
http://jsfiddle.net/mowglisanu/9xY46/58

非常感谢@Musa,这是一个将数据转换为base64string的简单函数。 在处理获取二进制文件的WebView中处理二进制文件(pdf,png,jpeg,docx,…)文件时,这可能会很方便,但是您需要将文件的数据安全地传输到您的应用程序中。

 // runs a get/post on url with post variables, where: // url ... your url // post ... {'key1':'value1', 'key2':'value2', ...} // set to null if you need a GET instead of POST req // done ... function(t) called when request returns function getFile(url, post, done) { var postEnc, method; if (post == null) { postEnc = ''; method = 'GET'; } else { method = 'POST'; postEnc = new FormData(); for(var i in post) postEnc.append(i, post[i]); } var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var res = this.response; var reader = new window.FileReader(); reader.readAsDataURL(res); reader.onloadend = function() { done(reader.result.split('base64,')[1]); } } } xhr.open(method, url); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send('fname=Henry&lname=Ford'); xhr.responseType = 'blob'; xhr.send(postEnc); }