jQuery의 ajax 메서드를 사용하여 이미지를 blob으로 검색


84

나는 최근에 또 다른 (관련) 질문을했는데,이 질문은 다음과 같은 후속 질문으로 이어졌습니다. 입력 양식을위한 파일 대신 데이터 제출

jQuery.ajax () 문서 ( http://api.jquery.com/jQuery.ajax/ )를 읽어 보면 허용되는 데이터 유형 목록에 이미지가 포함되어 있지 않은 것 같습니다.

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)

대신이 이미지를 blob으로 검색하려면 어떻게해야합니까?


서버 측에서 응답 유형을 변경해야한다고 생각합니다.
Eric Frick

필자가 소유 한 서버가 아닌 모든 URL에서 이미지를 가져 오려고합니다.
jabalsad


그 대답의 세 가지 해결책은 (1) <img> 태그를 사용하거나, (2) 서버가 이미지를 byte64 인코딩으로 제공하거나 (3) 브라우저의 캐시를 사용하는 것입니다. (2) 스크립트가 모든 이미지 URL을 작동하기를 원하기 때문에 제외되었습니다. 이미지를 다운로드 한 후에는 Blob으로 변환해야하므로 (1) 또는 (3)을 사용하는 방법을 잘 모르겠습니다.
jabalsad

옵션 3은 이미 이미지를 다운로드 한 경우에만 작동합니다. 처음으로 뭔가 다른 것이 필요할 것입니다. 1 번을 선택 하시겠습니까?
Eric Frick 2013

답변:


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

@jabalsad 질문은 질문 How can I retrieve this image as a blob instead?, 그냥 데모를했다 어쨌든, handler걸릴 this.response과 formdata 객체에 추가하고 아약스 통해 보낼 수 있습니다.
Musa

2
+1, 잘 작동합니다! : 그리고 참고로,이 마지막으로 jQuery를 곧 추가됩니다 수 github.com/jquery/jquery/pull/1525
lambshaanxy

9
2017 : jQuery는 여전히 'blob'유형을 처리 할 수 ​​없습니까?
robsch

1
'xhrFields'는 jQuery 2에서도 작동합니다 (2.2.4에서 테스트 됨)
Bampfer

15

당신이해야하는 경우 오류 메시지를 처리 하여 jQuery.AJAX을 당신은해야합니다 수정 xhr기능을 이 때문에 responseType오류가 발생할 때 수정되지 않습니다.

따라서 성공적인 호출 인 경우에만 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
    }
});

노트

xhr.responseType" blob "로 설정 한 직후에 중단 점을 디버그하고 배치 하면 값을 가져 오려고 responseText하면 다음 메시지가 표시됨을 알 수 있습니다 .

이 값은 개체의 'responseType'이 ''또는 'text'( 'blob'이전) 인 경우에만 액세스 할 수 있습니다.


1
대단히 감사합니다! 이것이 제가 찾던 해결책이었습니다. .done()메서드 에서 성공적인 응답을 "blob"(제 경우에는 ZIP 아카이브)로 처리하기 위해 AJAX가 필요했습니다. 문제가 발생하면 .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);
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.