sommeguyy sommeguyy - 1 month ago 5
Ajax Question

I can not return an image file and show it in View using Ajax in Asp.net MVC

$.ajax({
type: 'GET',
dataType: 'image/jpeg',
url: '/Home/GetImage/' + img ,
success: function (data) {
i = new Image();
i.src = data;
$('#imageresult').append(i);
},
error: function () {
alert('error');
},
});


[HttpGet]
public ActionResult GetImage(string img)
{
string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
var path = Path.Combine(imageFile, img );
var srcImage = Image.FromFile(path);
var stream = new MemoryStream();
srcImage.Save(stream, ImageFormat.Jpeg);

return File(stream.ToArray(), "image/jpeg");
}


It always falls into error function. If i remove dataType, then it doesn't fall into error function but it just shows long strings in the view. Why doesn't that work and show image in view?

SeM SeM
Answer

You can do something Like this:

public ActionResult GetImage(string img)
{
   string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Profile/Small/" );
   var path = Path.Combine(imageFile, img );  
   var srcImage = Image.FromFile(path);
   var stream = new MemoryStream();
   srcImage.Save(stream, ImageFormat.Jpeg);

   return Json(Convert.ToBase64String(stream.ToArray()), JsonRequestBehavior.AllowGet);
}

and the Ajax call:

$.ajax({
        type: 'GET',
        url: '@Url.Action("GetImage", "Home")',
        success: function (data) {
            $("#ItemPreview").attr('src', 'data:image/png;base64,' + data);
        },
        error: function () {
            alert('error');
        },
    });

and the view:

<img id="ItemPreview" src="" />

of course you can append img dynamically, then bind its source after.