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

时间:2011-04-28 09:47:55

标签: c# asp.net

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

4 个答案:

答案 0 :(得分:5)

  • 如果您打算保存文件 然后是Web服务器上的目录 Server.MapPath()将是合适的 溶液

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

    查看Here

  • 如果您打算保存文件 然后是网络服务器

    使用完整路径,例如“c:\ uploads” 并确保网络流程有 写入该文件夹的权限,我建议你在这种情况下将路径本身存储在web.config文件中。

答案 1 :(得分:3)

是的,可以在保存文件后以及尝试检索该文件时使用...

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

这是一行代码:

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