Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display images on a page when images are stored outside of web root

When users upload an image, it is stored in the file system but outside of what is publicly reachable.

I am displaying a list of items, and each item has an image associated with it.

How can I display the image when the actual file is stored outside of the wwwroot folder? i.e. it isn't publicly available.

like image 966
loyalflow Avatar asked Nov 02 '25 23:11

loyalflow


2 Answers

Since the action method is running on the server, it can access any file it has permission to. The file does not need to be within the wwwroot folder. You simply need to tell the action method which image to get.

For instance:

<img src="/mycontroller/myaction/123">

Your action would then look like:

public FileResult MyAction(int id)
{
    var dir = "c:\myimages\";
    var path = Path.Combine(dir, id + ".jpg");

    return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg");
}

Please note that the id is an int which will prevent someone from injecting a path to access different files on the drive/share.

like image 170
Cloud SME Avatar answered Nov 04 '25 14:11

Cloud SME


You could do this two ways.

Option 1, you could create a Virtual directory which points to this other Directory. This would then mean that you could access the images via another URL. e.g. Create a Virtual Directory called "OtherImages", then your URL would be;

http://www.mywebsite.com/otherimages/myimage.jpg

Option 2, you could create a simple HttpHandler which can load up the image from the absolute path, then output this in the response. Read up on HttpHandlers and dynamically generating images.

like image 25
Tim B James Avatar answered Nov 04 '25 16:11

Tim B James