2013-07-15 25 views
44

Gần đây tôi đã hỏi khác (liên quan) câu hỏi, mà dẫn theo dõi câu hỏi này: Submitting data instead of a file for an input formSử dụng phương pháp ajax jQuery để lấy hình ảnh như một blob

Đọc qua jQuery.ajax() tài liệu (http://api.jquery.com/jQuery.ajax/), nó có vẻ như danh sách các dataTypes được chấp nhận không bao gồm hình ảnh.

Tôi đang cố truy xuất hình ảnh bằng jQuery.get (hoặc jQuery.ajax nếu tôi phải), lưu trữ hình ảnh này trong Blob và tải nó lên máy chủ khác trong yêu cầu POST. Hiện tại, có vẻ như do sự không khớp trong các kiểu dữ liệu, hình ảnh của tôi sẽ bị hỏng (kích thước tính bằng byte không khớp, v.v.).

Các mã để thực hiện điều này là như sau (đó là trong coffeescript nhưng không nên rất khó để phân tích):

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) 

Làm thế nào tôi có thể lấy hình ảnh này như một blob để thay thế?

+0

Tôi nghĩ bạn phải thay đổi loại phản hồi ở phía máy chủ. –

+0

Tôi đang cố gắng kéo hình ảnh từ bất kỳ url nào, không phải máy chủ mà tôi sở hữu nhất thiết. – jabalsad

+0

hãy xem http://stackoverflow.com/questions/4285042/can-jquery-ajax-load-image –

Trả lời

73

Bạn không thể làm điều này với jQuery ajax, nhưng với XMLHttpRequest gốc.

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

EDIT

Vì vậy, xem xét lại vấn đề này, có vẻ như nó thực sự có thể làm điều này với 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%>

hoặc

xhrFields sử dụng để thiết lập các 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%>

+0

Cảm ơn. Tôi chỉ tìm ra và thấy câu trả lời của bạn. Nó tương tự như của tôi (khác với thực tế tôi đăng nó vào một hình thức thay vì đặt nó trên một đối tượng ).Tôi sẽ đánh dấu nó là chính xác anyway :) – jabalsad

+0

@jabalsad câu hỏi hỏi 'Làm thế nào tôi có thể lấy hình ảnh này như là một blob thay vì? ', Dù sao đó chỉ là để giới thiệu nó,' handler' sẽ có 'this.response' và thêm nó đến một đối tượng formdata và gửi nó qua ajax. – Musa

+2

+1, hoạt động tuyệt vời! Và FYI, điều này cuối cùng có thể được thêm vào jQuery sớm: https://github.com/jquery/jquery/pull/1525 – jpatokal

2

Chân thành cảm ơn bạn @Musa và đây là một chức năng gọn gàng có thể chuyển đổi dữ liệu vào một chuỗi base64. Điều này có thể hữu ích cho bạn khi xử lý tệp nhị phân (pdf, png, jpeg, docx, ...) trong một WebView nhận tệp nhị phân nhưng bạn cần chuyển dữ liệu của tệp một cách an toàn vào ứng dụng của bạn.

// 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); 
} 
Các vấn đề liên quan