[英]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.