【问题标题】:jQuery.ajax get image from wcf service and displayjQuery.ajax 从 wcf 服务获取图像并显示
【发布时间】:2015-01-21 02:57:51
【问题描述】:

我正在尝试使用 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 放入 &lt;img&gt; 标记中确实可以正确显示图像,但由于该服务需要授权标头,因此该页面每次都要求我提供凭据。

所以我的问题是,如何处理响应数据以便我可以显示它?使用 btoa();在响应上显示错误:

字符串包含无效字符

谢谢。

【问题讨论】:

  • 为什么响应 contentType 是 "application/x-www-form-urlencoded" ?不清楚身份验证问题是什么。假设它被发送的标头覆盖?
  • 因为服务可以返回任何类型的文件,但是对于这个特定的部分,我确定文件是图像。没有身份验证问题,问题出在我收到的数据上。
  • 图片与表单编码有什么关系?
  • 我不知道..这对我来说很新。而且我没有对服务进行编码,其他人做了。我几乎在做一些我不太了解的事情..
  • 嗯,你不能用 jQuery 做到这一点,你必须使用裸 XHR2

标签: javascript jquery ajax wcf


【解决方案1】:

按照 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-04
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    相关资源
    最近更新 更多