Using jQuery's ajax method to retrieve images as a blob

前端 未结 3 2224
南旧
南旧 2020-11-22 10:36

I recently asked another (related) question, which lead to this follow up question: Submitting data instead of a file for an input form

Reading through the jQuery.aj

3条回答
  •  礼貌的吻别
    2020-11-22 11:20

    You can't do this with jQuery ajax, but with native 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();      
    

    EDIT

    So revisiting this topic, it seems it is indeed possible to do this with 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(){
                
            }
        });
    
    

    or

    use xhrFields to set the 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(){
                    
                }
            });
    
        

提交回复
热议问题