使用Server.MapPath()和fileupload . savea()上传文件

本文关键字:文件 savea Server MapPath 使用 fileupload | 更新日期: 2023-09-27 17:53:21

我有一个网站管理部分,我正忙于工作,其中有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";
        }

使用Server.MapPath()和fileupload . savea()上传文件

  • 如果您打算将文件保存在那么,你的web服务器上的一个目录Server.MapPath()将是合适的解决方案。

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

  • 如果你想保存文件web服务器然后

    使用完整路径,如"c:'uploads"并确保web进程如果你没有权限写这个文件夹,我建议你把路径本身存储在网上。

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

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

是的,它应该仍然作为服务器工作。MapPath使用相对值并返回完整的物理路径。

一行代码:

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