Return StreamContent with ajax call

Hi Guys,
I am using asp.net MVC project.
I have an AJAX call from the UI side that goes to the server and return Picture as "StreamContent" (that is a type of .net class return).

Here is the way I call this method that returns StreamContent:

 function ClickTest() {
             var url = "http://demo.leadtools.com/images/pdf/leadtools.pdf"
             var ajaxOptions = {};
             ajaxOptions.cache = false;
             ajaxOptions.url = "http://localhost:20050/api/Raster/Load";
             ajaxOptions.type = "GET";
             ajaxOptions.headers = {};
             ajaxOptions.headers.Accept = "application/octet-stream";
             ajaxOptions.data = { uri: url, pageNumber: 1, resolution: 0, mimeType: "", bitsPerPixel: 0, qualityFactor: 0, imageWidth: 0, imageHeight: 0 };
             ajaxOptions.success = function (result) {
                 debugger;
                 console.log(result);
                 $("#imgid").html("<img src=" + result + ">");
                 //$("#imgid").html(result);
             };
             $.ajax(ajaxOptions);
         }

Open in new window


It seems that I get some binary result but when I place it in the dom I don't get the picture.

There is any way to convert this result and put it like a picture.

Example of the result I am getting.

LVL 1
Moti Mashiah.NET DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
You need to base64 encode the data and the add it like so in your AJAX complete
var base64Data = btoa(result);
 $("#imgid").html("<img src="data:image/jpeg;base64," + base64Data + ">");

Open in new window

Suggestion - don't use .success - this is being deprecated.
Rather do
$.ajax(ajaxOptions).done(function(resp) {
  var base64Data = btoa(result);
  $("#imgid").html("<img src="data:image/jpeg;base64," + base64Data + ">");
})

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
Alternative would be to base64 the string before sending it to the browser and simply adding the result to the img src string.
0
Moti Mashiah.NET DeveloperAuthor Commented:
Hi Julian,

Thank you for your answer.
I wrote something like:
function ClickTest() {
        var url = "http://demo.leadtools.com/images/pdf/leadtools.pdf"
        var ajaxOptions = {};
        ajaxOptions.cache = false;
        ajaxOptions.url = "http://localhost:20050/api/Raster/Load";
        ajaxOptions.type = "GET";
        ajaxOptions.headers = {};
        ajaxOptions.headers.Accept = "application/octet-stream";
        ajaxOptions.data = { uri: url, pageNumber: 1, resolution: 0, mimeType: "", bitsPerPixel: 0, qualityFactor: 0, imageWidth: 0, imageHeight: 0 };
        $.ajax(ajaxOptions).done(function(result){
            debugger;
            var base64Data = btoa(result);
            $("#imgDivid").html("<img src='data:image/jpeg;base64,''" + base64Data + "'>")
        });
    }

Open in new window


Now I am getting error on "btoa(result);"

"Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range."

Btw, what is BTOA method for?? I never use that before.

Thank you Julian.
0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Julian HansenCommented:
This might work better than the code above
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
	var blb = new Blob([xhr.response], {type: 'image/png'});
	var url = (window.URL || window.webkitURL).createObjectURL(blb);
	var image = document.createElement('img');
	image.src = url;
	document.getElementById('imgid').appendChild(image);
}

xhr.open('GET', '"http://localhost:20050/api/Raster/Load";');
xhr.send();

Open in new window

0
Julian HansenCommented:
Btw, what is BTOA method for?? I never use that before.
Converts binary to base64 - but it has varied results - my tests were a bit frustrating. I found the XHR process above to be the most reliable.
0
Moti Mashiah.NET DeveloperAuthor Commented:
Hi Julian,
I copied your javascript code above and I am getting error;

Failed to load file:///D:/Projects/LeadTools/%22http://localhost:20050/api/Raster/Load%22;: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

seems like the xhr.optn go to the local machine path instead to HTML protocol.
0
Julian HansenCommented:
Cut and paste error on my part
xhr.open('GET', '"http://localhost:20050/api/Raster/Load";');

Open in new window

Should be
xhr.open('GET', 'http://localhost:20050/api/Raster/Load');

Open in new window

0
Moti Mashiah.NET DeveloperAuthor Commented:
Julian,
The URL http://localhost:20050/api/Raster/Load contain params that I must pass to the method and I am not familiar with this XMLHttpRequest call.

can you tell me how can I pass params with the URL?

thank you.
0
Moti Mashiah.NET DeveloperAuthor Commented:
can I do something like   xhr.open('GET', 'http://localhost:20050/api/Raster/Load'+ url);
0
Moti Mashiah.NET DeveloperAuthor Commented:
like I need something like this:
  var url = "http://demo.leadtools.com/images/pdf/leadtools.pdf"
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'arraybuffer';
        xhr.onload = function () {
            var blb = new Blob([xhr.response], { type: 'image/png' });
            var url = (window.URL || window.webkitURL).createObjectURL(blb);
            var image = document.createElement('img');
            image.src = url;
            document.getElementById('imgDivid').appendChild(image);
            
        }

        xhr.open('GET', 'http://localhost:20050/api/Raster/Load' + url);
        xhr.send();

Open in new window

0
Moti Mashiah.NET DeveloperAuthor Commented:
k I got it.

 var url = "http://demo.leadtools.com/images/pdf/leadtools.pdf"
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'arraybuffer';
        xhr.onload = function () {
            var blb = new Blob([xhr.response], { type: 'image/png' });
            var url = (window.URL || window.webkitURL).createObjectURL(blb);
            var image = document.createElement('img');
            image.src = url;
            document.getElementById('imgDivid').appendChild(image);
            
        }

        xhr.open('GET', 'http://localhost:20050/api/Raster/Load/?uri=' + url);
        xhr.send();

Open in new window

0
Moti Mashiah.NET DeveloperAuthor Commented:
There is any other elegant way to pass these params?
0
Julian HansenCommented:
There is any other elegant way to pass these params?
Such as?
What is the problem with doing it this way?
0
Moti Mashiah.NET DeveloperAuthor Commented:
No problem.
I just like to do it in the way I do it with ajax call.

Thank you sooooooo much Julian.
0
Moti Mashiah.NET DeveloperAuthor Commented:
Thank you Julian.
0
Julian HansenCommented:
You are welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.