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

asp.net, asp.net-mvc, file-io

Solution

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.

Problem

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.

Original source