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

Eon*_*Eon 7 c# asp.net

我有一个网站管理员部分,我正在忙着工作,它有4个FileUpload控件用于特定目的.我需要知道,当我Server.MapPath()在FileUpload控件的SaveAs()方法中使用Method 时,在我上传网站后它是否仍然可以在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";
        }
Run Code Online (Sandbox Code Playgroud)

Any*_*are 5

  • 如果您打算将文件保存在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文件中.