Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an ASP.NET MVC controller return an Image?

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 requested:

www.mywebsite.com/resource/image/topbanner 

The controller will look up topbanner.png and send that image directly back to the client.

I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller.

Is this possible?

like image 477
Jonathan Avatar asked Oct 09 '08 05:10

Jonathan


People also ask

How to get image from controller in MVC?

You can get image from controller in MVC using the following C# code also public ActionResult GetImage() { string path = Server.MapPath ("~/images/computer.png"); byte [] imageByteData = System.IO.File.ReadAllBytes (path); return File (imageByteData, "image/png"); }

Can I return an image from an image file outside MVC?

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: 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)

How to add new controller in MVC project?

After creating MVC project, open Solution Explorer and add new empty controller. To add new controller, right click on the controller and select Add, then click Controller and create empty controller. I am creating a HomeController. namespace Returning_Image_From_Controller.Controllers

How to create MVC application in Visual Studio Code?

Select Installed Template, Visual C#, then click Web and select ASP.NET Web Application Project. Provide the name for project and click OK. Now one more dialog box will open and from that select Empty Project and check MVC Checkbox and press OK. After creating MVC project, open Solution Explorer and add new empty controller.


1 Answers

Use the base controllers File method.

public ActionResult Image(string id) {     var dir = Server.MapPath("/Images");     var path = Path.Combine(dir, id + ".jpg"); //validate the path for security or use other means to generate the path.     return base.File(path, "image/jpeg"); } 

As a note, this seems to be fairly efficient. I did a test where I requested the image through the controller (http://localhost/MyController/Image/MyImage) and through the direct URL (http://localhost/Images/MyImage.jpg) and the results were:

  • MVC: 7.6 milliseconds per photo
  • Direct: 6.7 milliseconds per photo

Note: this is the average time of a request. The average was calculated by making thousands of requests on the local machine, so the totals should not include network latency or bandwidth issues.

like image 167
Brian Avatar answered Oct 16 '22 12:10

Brian