簡體   English   中英

jQuery.ajax從wcf服務獲取圖像並顯示

[英]jQuery.ajax get image from wcf service and display

我正在嘗試下載並顯示使用jQuery.ajax從wcf服務返回的圖像。 我無法處理收到的數據,也不確定為什么。 我已經嘗試了很多東西,但似乎沒有任何效果。

這里的服務:

    public Stream DownloadFile(string fileName, string pseudoFileName)
    {
        string filePath = Path.Combine(PictureFolderPath, fileName);
        if (System.IO.File.Exists(filePath))
        {
            FileStream resultStream = System.IO.File.OpenRead(filePath);
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-www-form-urlencoded";
            return resultStream;
        }
        else
        {
            throw new WebFaultException(HttpStatusCode.NotFound);
        }
    }

這里我的ajax電話:

            $.ajax({
                type: "GET",
                url: apiURL + serviceDownloadFile.replace('{filename}', filename),
                headers: headers,
                contentType: "application/x-www-form-urlencoded",
                processData : false,
                success: function(response) { 
                    var html = '<img src="data:image/jpeg;base64,' + base64encode(response) +'">';
                    $("#activitiesContainer").html(html);
                },
                error: function (msg) {
                    console.log("error");
                    console.log(msg);
                }
            });

將url放在<img>標記中可以正確顯示圖像,但是由於該服務需要授權標頭,因此該頁面每次都要求我提供憑據。

所以我的問題是,該怎么做才能顯示響應數據? 使用btoa(); 在響應上顯示錯誤:

字符串包含無效字符

謝謝。

正如Musa建議的那樣,直接使用XMLHttpRequest可以達到目的。

            var xhr = new XMLHttpRequest();
            xhr.open('GET', apiURL + serviceDownloadFile.replace('{filename}', filename).replace('{pseudofilename}', fileNameExt), true);
            xhr.responseType = 'blob';
            xhr.setRequestHeader("authorization","xxxxx");

            xhr.onload = function(e) {
              if (this.status == 200) {
                var blob = this.response;

                var img = document.createElement('img');
                img.onload = function(e) {
                  window.URL.revokeObjectURL(img.src); // Clean up after yourself.
                };
                img.src = window.URL.createObjectURL(blob);
                document.body.appendChild(img);
              }
            };

            xhr.send();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM