Seyed Reza Amerizadeh
Seyed Reza Amerizadeh

Reputation: 52

How can get image with Jquery Ajax

I can can get picture by Razor '@Action' but with Ajax Can't. I write in controller:

        public ActionResult getCommodityPic()
    {
        var f= File(Server.MapPath("~/App_Data/CommodityPics/eee/1") + ".jpg", "image/jpg");
        return  f;
    }

and in java script :

    $(document).ready(function () {
    ShowCommodities();
    getCommodityPic();
});
function getCommodityPic() {
    $.ajax({
        url: '@Url.action("getCommodityPic")',
        type: 'Get',
        dataType: 'image/jpg',
        success: function (Data, Status, jqXHR) {
            $('#img1').attr('src', Data);
        }
    });

Upvotes: 2

Views: 5499

Answers (2)

Seyed Reza Amerizadeh
Seyed Reza Amerizadeh

Reputation: 52

        $.ajax({
            url: '@Url.Action("DownloadPic", "MyController")',
            contentType: 'application/json; charset=utf-8',
            datatype: 'json',
            data: {
                id: Id
            },
            type: "GET",
            success: function (Data, Status, jqXHR) {
                if (Data != "") {
                    alert("Empty");
                    return;
                }
                window.location ='@Url.Action("DonloadPic","Mycontroller")';
            }
        });

in Controller:

    public ActionResult DownloadPic(int? id)
    {
        Lesson l = new Lesson();
        l = db.Lesson.Single(p => p.id == id);

        if (l.picture == null)
        {
            string targetFolder = System.Web.HttpContext.Current.Server.MapPath("~/Image/book-03.jpg");
            byte[] img = System.IO.File.ReadAllBytes(targetFolder);
            return File(img, "image/jpg");
        }
        return File(l.picture, "image/jpg");
    }

Upvotes: 1

Shankar
Shankar

Reputation: 2825

If you want to display the image dynamically, then try this. You may not need an Ajax call for this.

$('#img1').html('<img src="getCommodityPic" />')

If you want to process the image (read its raw binary) then this answer should help - https://stackoverflow.com/a/20048852/6352160

Upvotes: 0

Related Questions