How to display images on a page when images are st

2020-07-25 08:51发布

问题:

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.

回答1:

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.



回答2:

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.