Can an ASP.NET MVC controller return an Image?

前端 未结 19 1637
旧时难觅i
旧时难觅i 2020-11-22 02:10

Can I create a Controller that simply returns an image asset?

I would like to route this logic through a controller, whenever a URL such as the following is requeste

相关标签:
19条回答
  • 2020-11-22 02:44

    UPDATE: There are better options than my original answer. This works outside of MVC quite well but it's better to stick with the built-in methods of returning image content. See up-voted answers.

    You certainly can. Try out these steps:

    1. Load the image from disk in to a byte array
    2. cache the image in the case you expect more requests for the image and don't want the disk I/O (my sample doesn't cache it below)
    3. Change the mime type via the Response.ContentType
    4. Response.BinaryWrite out the image byte array

    Here's some sample code:

    string pathToFile = @"C:\Documents and Settings\some_path.jpg";
    byte[] imageData = File.ReadAllBytes(pathToFile);
    Response.ContentType = "image/jpg";
    Response.BinaryWrite(imageData);
    

    Hope that helps!

    0 讨论(0)
  • 2020-11-22 02:47

    Why not go simple and use the tilde ~ operator?

    public FileResult TopBanner() {
      return File("~/Content/images/topbanner.png", "image/png");
    }
    
    0 讨论(0)
  • 2020-11-22 02:50
    if (!System.IO.File.Exists(filePath))
        return SomeHelper.EmptyImageResult(); // preventing JSON GET/POST exception
    else
        return new FilePathResult(filePath, contentType);
    

    SomeHelper.EmptyImageResult() should return FileResult with existing image (1x1 transparent, for example).

    This is easiest way if you have files stored on local drive. If files are byte[] or stream - then use FileContentResult or FileStreamResult as Dylan suggested.

    0 讨论(0)
  • 2020-11-22 02:51

    I also encountered similar requirement,

    So in my case I make a request to Controller with the image folder path, which in return sends back a ImageResult object.

    Following code snippet illustrate the work:

    var src = string.Format("/GenericGrid.mvc/DocumentPreviewImageLink?fullpath={0}&routingId={1}&siteCode={2}", fullFilePath, metaInfo.RoutingId, da.SiteCode);
    
                    if (enlarged)
                        result = "<a class='thumbnail' href='#thumb'>" +
                            "<img src='" + src + "' height='66px' border='0' />" +
                            "<span><img src='" + src + "' /></span>" +
                            "</a>";
                    else
                        result = "<span><img src='" + src + "' height='150px' border='0' /></span>";
    

    And in the Controller from the the image path I produce the image and return it back to the caller

    try
    {
      var file = new FileInfo(fullpath);
      if (!file.Exists)
         return string.Empty;
    
    
      var image = new WebImage(fullpath);
      return new ImageResult(new MemoryStream(image.GetBytes()), "image/jpg");
    
    
    }
    catch(Exception ex)
    {
      return "File Error : "+ex.ToString();
    }
    
    0 讨论(0)
  • 2020-11-22 02:52

    you can use File to return a file like View, Content etc

     public ActionResult PrintDocInfo(string Attachment)
                {
                    string test = Attachment;
                    if (test != string.Empty || test != "" || test != null)
                    {
                        string filename = Attachment.Split('\\').Last();
                        string filepath = Attachment;
                        byte[] filedata = System.IO.File.ReadAllBytes(Attachment);
                        string contentType = MimeMapping.GetMimeMapping(Attachment);
    
                        System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
                        {
                            FileName = filename,
                            Inline = true,
                        };
    
                        Response.AppendHeader("Content-Disposition", cd.ToString());
    
                        return File(filedata, contentType);          
                    }
                    else { return Content("<h3> Patient Clinical Document Not Uploaded</h3>"); }
    
                }
    
    0 讨论(0)
  • 2020-11-22 02:55

    To expland on Dyland's response slightly:

    Three classes implement the FileResult class:

    System.Web.Mvc.FileResult
          System.Web.Mvc.FileContentResult
          System.Web.Mvc.FilePathResult
          System.Web.Mvc.FileStreamResult
    

    They're all fairly self explanatory:

    • For file path downloads where the file exists on disk, use FilePathResult - this is the easiest way and avoids you having to use Streams.
    • For byte[] arrays (akin to Response.BinaryWrite), use FileContentResult.
    • For byte[] arrays where you want the file to download (content-disposition: attachment), use FileStreamResult in a similar way to below, but with a MemoryStream and using GetBuffer().
    • For Streams use FileStreamResult. It's called a FileStreamResult but it takes a Stream so I'd guess it works with a MemoryStream.

    Below is an example of using the content-disposition technique (not tested):

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetFile()
        {
            // No need to dispose the stream, MVC does it for you
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "myimage.png");
            FileStream stream = new FileStream(path, FileMode.Open);
            FileStreamResult result = new FileStreamResult(stream, "image/png");
            result.FileDownloadName = "image.png";
            return result;
        }
    
    0 讨论(0)
提交回复
热议问题