RealityDysfunction
RealityDysfunction

Reputation: 2639

Using Server.MapPath() to generate img src, not working

This seems like a basic question, but I am looking for a proper way of doing this. I am displaying a series of images and their source in view looks like this:

src="@Server.MapPath(Path.Combine("~/App_Data/",photo.ClientId.ToString(),photo.PhotoId.ToString())+photo.FileExt.ToString())"

Which compiles to:

"c:\users\architect\documents\visual studio 2012\Projects\PhotoManagement\PhotoManagement\App_Data\5\62.jpg"

I triple checked that the files do exist at this location. Why does the browser refuse to display this image? Is there a workaround so that the code still works on the server when I upload it.

Thanks.

Upvotes: 0

Views: 3275

Answers (2)

Richard Deeming
Richard Deeming

Reputation: 31198

Server.MapPath returns the path of the image on the server. Unless the client happens to have an image in exactly the same path on their computer, this will not work.

Try using Url.Content instead:

src="@Url.Content(Path.Combine("~/App_Data/", photo.ClientId.ToString(), photo.PhotoId.ToString()) + photo.FileExt.ToString())"

Upvotes: 1

Darren Wainwright
Darren Wainwright

Reputation: 30727

APP_Data is a restricted folder intended for Datasources such as Database only. ASP.Net will not deliver a file in here - try it by going to the URL for that image directly (I.E www.mysite/App_Data/5/62.jpg ) and you will see the error message HTTP Error 403 - Forbidden.

Put your images in a folder outside of this and you will be fine, such as a folder in the root Called Images

Upvotes: 2

Related Questions