[英]saving multiple file upload server.mappath give DirectoryNotFoundException asp.net
我正在尝试使用文件上传选择多个图像并将其保存到目录中,目的是显示图像url,我不使用任何插件进行多次上传
所以这是设计师:
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" onchange="updateList()"/> <br/>
<asp:Button ID="Button4" runat="server" Text="Upload File" onclick="Button4_Click"/>
如果我执行单个文件upload.now,则无法正常工作,我正在尝试同时保存更多图像,这是我的代码背后:
if (FileUpload1.HasFile)
{
int i = 0;
foreach (var img in FileUpload1.PostedFiles)
{
string filePath = img.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = string.Empty;
switch (ext)
{
case ".jpg":
contenttype = "image/jpg";break;
case ".png":
contenttype = "image/png";break;
case ".gif":
contenttype = "image/gif";break;
}
if (contenttype != String.Empty)
{
try
{
string fullpath= Server.MapPath("~/images/TmpE/" + filename + "");
img.SaveAs(fullpath);
ClientScript.RegisterStartupScript(GetType(), "successupload" + i, @"uploadSuccess('" + fullpath + "');", true);
i++;
}
catch (Exception ex)
{
Label2.Text = "exception : " + ex.ToString();
}
}
}
}
但是此代码始终会捕获异常:
System.IO.DirectoryNotFoundException:找不到路径“ C:\\ ClientSites \\ sample.com \\ httpdocs \\ images \\ TmpE \\ sample.png”的一部分
正如您在评论中写道:
“是的,我已验证,并且目录不存在”
然后,您收到此错误消息也就不足为奇了。 如果您要求服务器将文件保存在不存在的目录中,则会抛出DirectoryNotFoundException
。
更改您的行:
Server.MapPath("~/images/TmpE/" + filename + "");
到确实存在的目录(并且具有足够的写特权)
或者,手动或通过代码( File.Directory.CreateDirectory
)创建目录C:\\ClientSites\\sample.com\\httpdocs\\images\\TmpE\\
(同样,具有足够的写File.Directory.CreateDirectory
)。
例如:
string savePath = Server.MapPath("~/images/TmpE/");
if (!Directory.Exsits(savePath))
Directory.CreateDirectory(savePath);
// Now you've made sure the directory exists, save the file.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.