Download files using Server.MapPath () and FileUpload.SaveAs ()

I have a site administration section that I'm working on and has 4 FileUpload controls for specific purposes. I need to know that when I use the Server.MapPath() method Server.MapPath() controls, will it still be used on the web server after I load the website? As far as I know, SaveAs() requires an absolute path, so I map the path to Server.MapPath()

 if (fuLogo.HasFile) //My FileUpload Control : Checking if a file has been allocated to the control { int counter = 0; //This counter Is used to ensure that no files are overwritten. string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' }); logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]); // This is the part Im wondering about. Will this still function the way it should on the webserver after upload? if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG") { while (System.IO.File.Exists(logo)) { counter++; //Here the counter is put into action logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]); } } else { cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again."; cvValidation.IsValid = false; } if (fuLogo.PostedFile.ContentLength > 409600 ) //File must be 400kb or smaller { cvValidation.ErrorMessage = "Please use a picture with a size less than 400 kb"; cvValidation.IsValid = false; } else { if (fuLogo.HasFile && cvValidation.IsValid) { fuLogo.SaveAs(logo); //Save the logo if file exists and Validation didn't fail. The path for the logo was created by the Server.MapPath() method. } } } else { logo = "N/A"; } 
+7
source share
4 answers
  • If you are going to save the files to a directory on your web server, then Server.MapPath() would be the appropriate solution.

    string dirPath = System.Web.HttpContext.Current.Server.MapPath("~") + "/Images/Logos/"+ fileBreak[0] + counter.ToString() + "." + fileBreak[1];

    Look here

  • if you want to save your web server files then

    Use the full path, for example, "c: \ uploads" and make sure that the web process has write permission to this folder, I suggest you save this path in the web.config file in this case.

+4
source

Yes, which can be used after saving the file and when trying to get this file ...

 Server.MapPath("~/Images/Logos/" + uploadedFileName); 
+3
source

Yes, it should work like Server.MapPath uses relative values ​​and returns the full physical path.

0
source

This is one line of code:

  FileUpload1.PostedFile.SaveAs(Server.MapPath(" ")+"\\YourImageDirectoryOnServer\\"+FileUpload1.FileName); 
0
source

All Articles