问题
So I'm attempting to create an application that displays images saved on a certain folder. Each user has a different folder on the C drive from which the images will be pulled from.
Currently I'm using:
@foreach (var imgPath in Directory.GetFiles("C:/Users/me/documents", "*.*"))
{
var img = new FileInfo(imgPath);
<img src="@Url.Content(String.Format("C:/Users/me/documents/{0}", img.Name))" />
}
However this does not display the image because of the C path but scouring the web has led me nowhere other than someone saying you could make a virtual path and point it to a physical one but I could not find a tutorial on that.
I would like to also make the me
part variable as each user would have their own folder but I'm not sure if this can be handled in a controller.
回答1:
Url.Content
helper method takes a virtual content path to your file and returns a url to access the file in your site. You should not be passing a physical directory location to that.
You may consider saving the images in your web app. Create a directory called "Images" and then you can safely use Url.Content method.
For example,
@foreach (var imgPath in Directory.GetFiles(Server.MapPath(Url.Content("~/Images/"))))
{
<img src="@Url.Content("~/Images/"+ @Path.GetFileName(imgPath))" />
}
Or If you absolutely need to store the images somewhere outside the app root,(Ex : "C:\temp\images or a network location), You might consider creating an action method which takes the file name, read the file from the location and return as an image.
public ActionResult GetImg(string id)
{
var path = $@"C:\temp\images\{id}.png";
var bytes = System.IO.File.ReadAllBytes(path);
return File(bytes, "image/png");
}
Now you simply need to call this end point and use that as the image src property.
@foreach (var imgPath in Directory.GetFiles(@"C:\temp\images", "*.*"))
{
<img src="@Url.Action("GetImg",new {id=Path.GetFileNameWithoutExtension(imgPath)})" />
}
The above is a simple solution where i hard coded it to return png files. you can update it to be more flexible (add a param to accept the file extension as well)
Note : I personally prefer to keep minimal C# in razor files. I like to move the C# code (all those Directory.GetFiles
lines) to the GET action and pass the list of image names to the view via a view model/view bag(as needed).
来源:https://stackoverflow.com/questions/42378418/display-images-from-c-path-or-change-where-virtual-path-points-to