if( filMyFile.PostedFile != null )
{
// File was sent
}
else
{
// No file
}
再利用 PostedFile 的 SaveAs 方法來進行寫入檔案的動作, 但以上的作法要配合 runat server 的 html web control 來進行, 若是要搭配 asp 或是單純的 html 來進行寫入檔案, 應該如何進行呢? 可以利用 Request.Files 來進行, 而且可以同時傳遞多檔, 更容易地進行處理, 以下為取出所有檔案並存檔的一個範例程式:
代碼: 選擇全部
string saveFiles() {
string strMessage = "";
string strFileName;
HttpPostedFile objFile;
for (int i=0; i<Request.Files.Count; i++) {
objFile = Request.Files[i];
if (objFile.FileName != "") {
strFileName = objFile.FileName;
strFileName = strFileName.Substring(strFileName.LastIndexOf("\")+1);
try {
objFile.SaveAs("c:\temp\"+strFileName);
strMessage+= "Uploaded: c:\temp\"+strFileName+"<br>";
}
catch (Exception err) {
strMessage+= "Failed uploading "+strFileName+": "+err.ToString()+"<br>";
}
}
}
return strMessage;
}
如此一來便能不使用 runat server 的元件來進行 asp.net file upload 的功能!!
參考文件,
1. 搭配 runat server 的作法,
http://www.codeproject.com/aspnet/fileupload.asp
http://www.freevbcode.com/ShowCode.Asp?ID=2136
http://msdn.microsoft.com/library/defau ... stopic.asp
http://www.wimdows.net/articles/printme.aspx?aid=4
2. 不使用 runat server 就是利用
http://www.wimdows.net/articles/printme.aspx?aid=4
的第二部分, multi-file 的 upload 來進行撰寫的, 其實就是利用了 Response.Files 來進行的, 如此一來, 前一頁無論是 asp 或是 html 等靜態頁面, 與本 aspx 頁面無關的 web page 皆可進行 file upload, 將能更方便的操作 file upload!!