Riquelmy Melara
Riquelmy Melara

Reputation: 941

Display Image using AJAX

I am trying to display a picture that I am calling from the controller using AJAX, this is my code:

<div id="productImg" style="display:none;">

</div>


<script>
    function showPic(id) {

        $.ajax({
            type: "GET",
            url: "/Equipment/GetImage",
            data: { 'productId': id },
            success: function (data) {
                $("#productImg").html(data)

            }
        });
</script>

And the method on my controller looks like this:

public virtual FileContentResult GetImage(int productId) {
  Product prod = _db.Products.FirstOrDefault(p => p.ProductID == productId);
  if (prod != null) {
    return File(prod.ImageData, prod.ImageMimeType);
  } else {
    return null;
  }
}

What I am getting is a lot of code and not the image. What else could I try?

Upvotes: 1

Views: 977

Answers (2)

Anubhav Ranjan
Anubhav Ranjan

Reputation: 1598

Please modify your Action method to something like this:

public virtual ActionResult GetImage(int productId)
{
    Product prod = _db.Products.FirstOrDefault(p => p.ProductID == productId);
    if (prod != null)
    {
        return new FileStreamResult(prod.ImageData, prod.ImageMimeType);
    }
    else
    {
        return null;
    }
}

Let me know if this works... Alternatively, what you can do is, you can prepend some text to the image data coming from the ajax call to display the image. All you have to do is, just prepend

data:image/png;base64,

where image/png is the mime-type.

Then when you push your src to the image tag the src will look something like this...

<img src="data:image/png;base64,     
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP 
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA 
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J 
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq 
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0 
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" />

Hope it works...

Upvotes: 0

David
David

Reputation: 218828

You don't need to use AJAX for this. Images are separate resources for a page and are loaded as separate requests already. Just link to it:

<div id="productImg">
    <img src="/Equipment/GetImage?productId=123" alt="Product" />
</div>

For making that happen dynamically in JavaScript, all you need to do is change that src value:

function showPic(id) {
    $('#productImg img').src = '/Equipment/GetImage?productId=' + id;
}

As an aside, the reason your approach doesn't work is because what you're getting back from the server isn't HTML, it's the raw image data. The HTML to display an image is not the image data itself, it's just an img tag with a URL. (That URL can contain an encoded copy of the actual data, but it really doesn't need to in this case.)

Upvotes: 2

Related Questions