使用Server.MapPath()和FileUpload.SaveAs()进行文件上传

我有一个网站管理员部分,我正在忙着工作,它有4个FileUpload控件用于特定目的。 我需要知道,当我在FileUpload控件的SaveAs()方法中使用Server.MapPath()方法时,在我上传网站后它是否仍然可以在Web服务器上使用? 据我所知, SaveAs()需要一个绝对路径,这就是我用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"; } 

  • 如果要将文件保存在Web服务器上的目录中,则Server.MapPath()将是合适的解决方案。

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

    看这里

  • 如果您打算将文件保存到Web服务器之外

    使用完整路径,例如“c:\ uploads”并确保Web进程有权写入该文件夹,我建议您将路径本身存储在web.config文件中。

是的,可以在保存文件后使用,当您尝试检索该文件时…

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

是的,它应该仍然有效,因为Server.MapPath使用相对值并返回完整的物理路径。

这是一行代码:

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