Development Tip

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

yourdevel 2020. 11. 14. 11:10
반응형

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


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

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으로 검색하려면 어떻게해야합니까?


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%>


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) {
        console.error(xhr.responseText); //Here you are able now to access to the property responseText as you have the type set to text instead of blob.
    },
    success: function(data) {
        console.log(data); //Here is blob type
    }
});

참고 : 디버그하고 xhr.responseType을 "blob"으로 설정 한 직후에 중단 점을 배치하면 "responseText"에 대한 값을 가져 오려고하면 다음 메시지가 표시됩니다.

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').


A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// 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);
}

참고URL : https://stackoverflow.com/questions/17657184/using-jquerys-ajax-method-to-retrieve-images-as-a-blob

반응형