views:

73

answers:

1

Hi All, Im adding the ability to upload images to my ASP.net mvc application. Basically the user selects an image and I upload it to an Images folder which i've created in my solution folder structure. This works great and the image uploads to the images folder.

The problem I have is now displaying the image back to the browser. My question is how do I change directory browsing properties of the Asp.net Development Server (localHost:blah blah) so that the images directory i.e. http://localHost:9823/Images/UploadedImageName.jpg shows up in the browser?

Thanks in advance

+1  A: 

A couple options that I've used. Pros and cons to each style!

In The View

You could have your Views configured to use this style:

 <img src="<%=ResolveUrl("~/Images/foo.png")" %> />

This could be refactored a handful of ways. An extension method perhaps, or codebehind your View.

Controller Method + Route

Create a new Controller to serve up images. Ensure you have a route with a default.

 public class Images
 {
   public FileResult GetImage(string fileName) //foo.png
    {
        string fullPath = "~/Images/" +  fileName;
        return base.File(fullPath, "image/jpeg");
    }
 }

...
routes.MapRoute("UserImage",
                "Image/{filename}",
                new { controller = "Images", action = "GetImage", 
                      fileName=filename });
p.campbell
You must validate the filename to prevent path traversal. (eg, `fileName=..\web.config`)
SLaks