복붙노트

[JQUERY] jQuery의 아약스 방법을 사용하여 BLOB으로 이미지를 검색

JQUERY

jQuery의 아약스 방법을 사용하여 BLOB으로 이미지를 검색

해결법


  1. 1.당신은 jQuery를 아약스와 함께이 작업을 수행하지만, 기본 XMLHttpRequest의와 수 없습니다.

    당신은 jQuery를 아약스와 함께이 작업을 수행하지만, 기본 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 및 자르기 = 엔트로피 CS & = (sRGB)의 & ixid = eyJhcHBfaWQiOjE0NTg5fQ % 3D % 3D & S = 471ae675a6140db97fea32b55781479e' 캐시 : 거짓, XHR : 함수 () {//는 XHR 객체에 대한 액세스 권한을 얻을 수있는 유일한 방법처럼 보인다 VAR의 XHR = 새로운 XMLHttpRequest 객체 (); xhr.responseType = '방울' XHR 반환; }, 성공 : 기능 (데이터) { VAR IMG = document.getElementById를 ( "IMG"); VAR URL = window.URL || window.webkitURL; img.src url.createObjectURL = (데이터); }, 오류 : 함수 () { } }); <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js">

    또는

    responseType을 설정 xhrFields를 사용

    jQuery.ajax ({ URL '은 https : //images.unsplash.com/photo-1465101108990-e5eac17cf76d ixlib = RB-0.3.5 & Q = 85 & FM = JPG 및 자르기 = 엔트로피 CS & = (sRGB)의 & ixid = eyJhcHBfaWQiOjE0NTg5fQ % 3D % 3D & S = 471ae675a6140db97fea32b55781479e' 캐시 : 거짓, xhrFields : { responseType : '방울' }, 성공 : 기능 (데이터) { VAR IMG = document.getElementById를 ( "IMG"); VAR URL = window.URL || window.webkitURL; img.src url.createObjectURL = (데이터); }, 오류 : 함수 () { } }); <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js">


  2. 2.당신이 jQuery.AJAX를 사용하여 오류 메시지를 처리해야하는 경우 오류가 발생하는 경우 responseType이 수정되지 않는, 그래서 당신은 XHR 기능을 수정해야합니다.

    당신이 jQuery.AJAX를 사용하여 오류 메시지를 처리해야하는 경우 오류가 발생하는 경우 responseType이 수정되지 않는, 그래서 당신은 XHR 기능을 수정해야합니다.

    당신은 호출이 성공한 경우에만 "덩어리"에 responseType을 수정해야합니다 그래서 :

    $.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을 설정 한 후 시점에서 중단 점을 배치하면 당신은 당신이에서 responseText에 대한 값을 얻을하려고하면 다음과 같은 메시지를 받게됩니다 참고 수 :


  3. 3.큰는 @Musa에게 감사하고 여기에 깔끔한 기능입니다 base64로 문자열로 변환 된 데이터를. 바이너리 파일을 가져옵니다 웹보기에서 이진 파일 (PDF, PNG, JPEG, DOCX, ...) 파일을 처리 할 때이 당신에게 편리하게 올 수 있지만, 앱으로 안전하게 파일의 데이터를 전송해야합니다.

    큰는 @Musa에게 감사하고 여기에 깔끔한 기능입니다 base64로 문자열로 변환 된 데이터를. 바이너리 파일을 가져옵니다 웹보기에서 이진 파일 (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);
    }
    
  4. from https://stackoverflow.com/questions/17657184/using-jquerys-ajax-method-to-retrieve-images-as-a-blob by cc-by-sa and MIT license