ASP.NET MVC and linked photos on shared folder
I'm writing asp.net mvc web application that uses a large number of .jpg files that are on a share folder outside the web server and not accessible via http protocol.
How can I place image path inside img开发者_如何学编程 tag?Do not put the image path inside your image tag as a parameter to a script. This is called a direct object reference and is a bad thing. Consider a naive implementation of such a script/page/controller which serves up as /image/?resource=\server\path\img.jpg.
Now what happens if someone loads /image/resource/?resource=c:\windows\system32\config\SAM? Your password database gets sent.
You do not want to use fully qualified paths at all, ideally you want to either serve all images from that directory and just accept a file name, stripping any path information from it by doing something like
string filename = Path.GetFileName(userInputtedFilename);
FileInfo file = new FileInfo(Server.Path.Combine("\\Server\share\", filename)));
That at least is safe, but of course users could browse through all the images if they're suitably named. Safer yet is to have an indirect object reference, a mapping table somewhere which maps something like a GUID to the actual filename and use that as the parameter to your serving script.
To serve a file you return a FileContentResult from your controller,
public FileContentResult GetFile(Guid indirectReference)
{
byte[] fileContents = // Resolve the file and read it from the indirect reference
mimeType = // Suitable MIME type
return File(fileContent, mimeType, fileName);
}
If the web server has regular network access to that share and can read the image files, you can create a new MVC controller Image
with default action Index
that takes one string parameter called fn
. The action would create a new FileResult
from the parameter. Then, when you generate the <img>
tag, set the url to something like /image/?fn=\\share\image.png
. (Don't forget to add the proper route for it, of course)
If the web server has no access to that share, but the page user has access, you can try setting the <img>
tag to the file://
URL for the image. However, this is going to be fragile and might or might not work, depending on the user's OS and browser configuration.
Update: Do read the security implications @blowdart mentioned in his answer.
精彩评论