简体   繁体   中英

jQuery.ajax get image from wcf service and display

I'm trying to download and display an image that is returned from a wcf service using jQuery.ajax. I'm not able to work with the data I've received and I'm not sure why. I've tried a lot of things but nothing seems to work.

Here the service :

    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);
        }
    }

Here my ajax call :

            $.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);
                }
            });

Putting the url in a <img> tag does display the image properly, but since the service requires an authorization header, the page ask me for credentials each time.

So my question is, what to do this the response data so I can display it ? using btoa(); on the response displays an error :

string contains an invalid character

Thanks.

As suggested by Musa, using XMLHttpRequest directly did the trick.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM