Save file in a folder above the site files
My host has the following structure:
/Web -> Where is the content of the site /Data -> Fol开发者_Go百科der permissions to read and write
How do I upload a file to the Data folder? The code below does not work, since "~" returns the directory / web.
//Save Image
var serverPath = Server.MapPath(Href("~/Data/") + id);
Directory.CreateDirectory(serverPath);
imgOri.Save(Path.Combine(serverPath, fileName));
Server.MapPath() is designed to map a path up to the root directory of the application. As you are trying to upload a file above the root it won't work.
You can upload a file above the root by specifying the exact file path (if the host can provide it):
var serverPath = "C:\YourFolder\Data\") + id);
I'm surprised your host is allowing you to upload a file outside of the root directory as there are a number of dangers in doing this...you may also run into Trust issues.
You can obtain the path to a directory which sits at the same level of your site root by using Server.MapPath as below:
@{
var root = Server.MapPath(".");
var temp = root.Split('\\');
temp[temp.Length - 1] = "Data";
var newpath = string.Join("\\", temp);
}
Hosting companies used to provide "data" directories outside of the root folder as a safe place for things like Access mdb databases. You cannot directly browse to a directory which is outside of the root of your site. ASP.NET did away with the need for these things with the introduction of App_Data
. The only reason you would want to use this kind of folder nowadays is if you want to apply some kind of authentication prior to serving the contents of the directory. Then you need to use a handler, or a simple cshtml file will do. You can combine the WebSecurity
helper with the WebImage
helper to first authenticate the user, and then retrieve and display the image if they pass the test. The src
in your img
tag will point to the cshtml file, with a querystring or UrlData
value so you know which image to display.
If you don't need to validate users prior to displaying image, storing the image files outside of the root adds an unnecessary level of complication.
精彩评论