使用jQuery的ajax方法将图像检索为斑点


84

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

阅读jQuery.ajax()文档(http://api.jquery.com/jQuery.ajax/),似乎可接受的dataTypes列表不包含图像。

我正在尝试使用jQuery.get(或必要时使用jQuery.ajax)来检索图像,将此图像存储在Blob中,然后在POST请求中将其上传到另一台服务器。当前,由于数据类型不匹配,我的图像最终被损坏(字节大小不匹配等)。

执行此操作的代码如下(它在coffeescript中,但应该不难解析):

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)

我如何检索此图像作为斑点?


我认为您必须在服务器端更改响应类型。
埃里克·弗里克

我正在尝试从任何URL中提取图像,而不是从我自己拥有的服务器中提取图像。
jabalsad 2013年


似乎该答案中的三个解决方案是(1)使用<img>标记,(2)使服务器以字节64编码的形式提供图像,或(3)使用浏览器的缓存。(2)被排除,因为我希望脚本可以处理任何图像URL。我不确定如何使用(1)或(3),因为下载图像后,我需要将其转换为Blob。
jabalsad 2013年

选项3仅在您已经下载图像后才起作用。第一次,您将需要一些不同的东西。也许选择1?
埃里克·弗里克

Answers:


146

您无法使用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();      

编辑

因此,回顾这个​​主题,似乎确实有可能使用jQuery 3做到这一点。

jQuery.ajax({
        url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',
        cache:false,
        xhr:function(){// Seems like the only way to get access to the xhr object
            var xhr = new XMLHttpRequest();
            xhr.responseType= 'blob'
            return xhr;
        },
        success: function(data){
            var img = document.getElementById('img');
            var url = window.URL || window.webkitURL;
            img.src = url.createObjectURL(data);
        },
        error:function(){
            
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<img id="img" width=100%>

要么

使用xhrFields设置responseType

    jQuery.ajax({
            url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',
            cache:false,
            xhrFields:{
                responseType: 'blob'
            },
            success: function(data){
                var img = document.getElementById('img');
                var url = window.URL || window.webkitURL;
                img.src = url.createObjectURL(data);
            },
            error:function(){
                
            }
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <img id="img" width=100%>


谢谢。我刚弄清楚,看到了你的答案。它类似于我的(除了我将其发布到表单而不是将其设置在<img>对象上的事实)。无论如何,我都会将其标记为正确:)
jabalsad 2013年

@jabalsad提出的问题How can I retrieve this image as a blob instead?无论如何只是为了演示它,handler将把它this.response添加到formdata对象中并通过ajax发送。
穆萨

2
+1,效果很好!仅供参考,这可能最终会很快添加到jQuery中:github.com/jquery/jquery/pull/1525
lambshaanxy 2014年

9
2017:jQuery仍然无法处理'blob'类型吗?
robsch

1
'xhrFields'也可以在jQuery 2中使用(在2.2.4中进行了测试)
Bampfer

15

如果您需要使用jQuery.AJAX处理错误消息,则需要修改该函数,以便在发生错误时不会对其进行修改。xhrresponseType

因此,只有在成功调用后,才需要将其修改responseType为“ blob ”:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

注意

如果在将blob设置xhr.responseTypeblob之后调试并在该点处放置断点,则可以注意到,如果尝试获取该值,responseText则会收到以下消息:

仅当对象的“ responseType”为“”或“文本”(为“ blob”)时,才可以访问该值。


1
非常感谢你!这是我一直在寻找的解决方案。我需要AJAX在该.done()方法中将成功的响应处理为“ blob”(在我的情况下为ZIP存档),如果出现问题,该.fail()方法中的响应应作为“文本”处理,因为否则responseText为空等。解决方案非常适合我!
informatik01

4

非常感谢@Musa,这是一个精巧的函数,可将数据转换为base64字符串。在获取二进制文件的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);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.