简体   繁体   中英

How to update image returned as File in ASP.NET MVC Controller using Ajax?

I have a base image, and I use C# Graphics library to add data to it, and then return the image converted to byte array.

I have a controller:

    public ActionResult DisplayDR(int drNum)
    {
        ER dr = DataUtility.getDR(drNum, errors);
        return File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png");
    }

That works fine with,

<img id="drImage" src="@Url.Action("DisplayDR")" width="1110"  height="484" alt="qr code" />

I need to be able to dynamically update the image and attempted with ajax with no luck.

Using: function getNewDRImage(instance) {

  var drNum = $(instance).data('val');
  var src = '@Url.Action("DisplayDR", "Home", new { area = "Part" })';
  $.ajax({
      type: "GET",
      url: src,
      data: { drNum : drNum },
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      error: function (err) {
          var msg = "Client side error, " + err;
          throwClientSideErrorMsg(msg)
      },
      success: function (data) {
         $('#drImage').attr("src", data.image);
      }
  });

}

and returning JSON like so,

    public JsonResult DisplayDMR(int drNum)
    {
        ER dr = DataUtility.getDR(drNum, errors);
        return
            Json(new { image = File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png") }, JsonRequestBehavior.AllowGet);
    }

Gives me this error:

System.Web.HttpException (0x80004005): The controller for path '/[object Object]' was not found or does not implement IController.

What am I not doing correctly?

update, viewing the source after the ajax call I see why the error occurs, as this is what the response is:

<img id="dmrImage" src="[object Object]" alt="qr code" height="484" width="1110">

So I guess I am confused on what to do with the JSON data to update the image.

With your ajax code you're trying to load actual bytes of your image and assign that to the src attribute. That's not what the attribute expects.

All you need is to just assign a new image url as a string. The browser then will automatically fetch actual bytes and show the new image for you.

If you want to use the same url for the updated image you need to make sure the browser won't use your old cached image. Take a look at this answer for how to do this.

To add Cache-Control: header to your File() response use Response.AddHeader() method:

public ActionResult DisplayDR(int drNum)
{
    Response.AddHeader("Cache-Control", "no-store");
    ER dr = DataUtility.getDR(drNum, errors);
    return File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png");
}

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