ajax請求二進制流圖片並渲染到html中img標簽


日常顯示圖片都諸如這種形式:直接使用img的src屬性

<img src="圖片路徑、地址" alt="" />

以上方法無法在獲取圖片請求中設置請求頭(headers)中字段

 

方法二:

var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://10.10.0.62:10001/api/charge/admin/v1/image/code",true);
xmlhttp.responseType = "blob";
xmlhttp.onload = function(){
    console.log(this);
    if (this.status == 200) {
        var blob = this.response;
        var img = document.createElement("img");
        img.onload = function(e) {
            window.URL.revokeObjectURL(img.src); 
        };
        img.src = window.URL.createObjectURL(blob);
        document.body.appendChild(img); 
    }
}
xmlhttp.send();
默認情況下,在發送XHR請求(request)的同時,還會發送下列頭部信息:
Accept:瀏覽器能夠顯示的字符集。
Accept-Charset:瀏覽器能夠顯示的字符集。
Accept-Encoding:瀏覽器能夠處理的壓縮編碼。
Accept-Language:瀏覽器當前設置的語言。
Connection: 瀏覽器與服務器之間的連接類型。
Cookie:當前頁面設置的任何cookie
Host:發出請求的頁面所在域。
Referer:發出請求的頁面的URL.(該單詞正確拼法是referrer)
User-Agent:瀏覽器的用戶代理字符串。

 

jquery優化版:

function imgFun (url, auth, img) {
                    var windowUrl = window.URL || window.webkitURL;//處理瀏覽器兼容性
                    var xhr = new XMLHttpRequest();
                    xhr.open("GET", url, true);
                    xhr.responseType = "blob";
                    xhr.setRequestHeader("Authorization", 'Bearer ' + auth.token);
                    xhr.onload = function () {
                        console.log(this);
                        if (this.status == 200) {
                            var blob = this.response;
                            $(img).load(function (e) {
                                windowUrl.revokeObjectURL(img.src);
                            }).attr("src", windowUrl.createObjectURL(blob));
                        }
                    }
                    xhr.send();
                }

imgFun("/common/download/rgPhoto/" + d.result, auth, $("#rgPhotoImg");

 

參考:

1.ajax請求二進制流圖片並渲染到html中img標簽

2.XML DOM - XMLHttpRequest 對象


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM