ASP.NET使用FileUpload上傳文件

ASP.NET使用FileUpload上傳文件

FileUpload 您需要親自將 enctype="multipart/form-data" 添加到頁面的 <form> 元素中

清單. FileUpload 控件生成的源代碼

 

<HTML xmlns="http://www.w3.org/1999/xHTML" >
<head><title>
   Upload Files
</title></head>
<body>
    
<form name="form1" method="post" action="MyFileUpload.ASPx" 
     id
="form1" enctype="multipart/form-data">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNDcxNTg5NDg3D2QWAgIEDxYCHgdlbmN0eXBlBRNtdWx0aXBhcnQvZm9yb
       S1kYXRhZGQUQEUFMY1+/fp1mnrkbqmVNQIzFA=="
 />
</div>

    
<div>
        
<input type="file" name="FileUpload1" id="FileUpload1" /><br />
        
<br />
        
<input type="submit" name="Button1" value="Upload File" 
         id
="Button1" /> <br />
        
<br />
        
<span id="Label1"></span>
    
</div>
    
<div>

   
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" 
    value
="/wEWAgLB+7jIAwKM54rGBv2Iz6LxVY7jWec0gZMxnuaK2ufq" />
</div></form>
</body>
</HTML>

 

確定可以上傳:定位到保存上傳的文件夾(用IE)——屬性——安全——是否有ASPNET帳戶 沒則加

去掉上傳大小限制:在 web.config.comments 文件(可以在 C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/CONFIG 的 ASP.NET 2.0 配置文件夾中找到)或應用程序的 web.config 文件中進行一些改動
在 web.config.comments 文件中,查找一個名爲 <executionTimeout>的節點
<httpRuntime
 executionTimeout="110" 上傳時間
 maxRequestLength="4096" 大小
 requestLengthDiskThreshold="80"
 useFullyQualifiedRedirectUrl="false"
 minFreeThreads="8"
 minLocalRequestFreeThreads="4"
 appRequestQueueLimit="5000"
 enableKernelOutputCache="true"
 enableVersionHeader="true"
 requireRootedSaveASPath="true"
 enable="true"
 shutdownTimeout="90"
 delayNotificationTimeout="5"
 waitChangeNotification="0"
 maxWaitChangeNotification="0"
 enableHeaderChecking="true"
 sendCacheControlHeader="true"
 apartmentThreading="false" />
在 web.config.comments 文件中進行此改動會將該設置應用於服務器上的所有應用程序。如果要將該設置僅應用於正在使用的應用程序,則將該節點應用於應用程序的 web.config 文件,覆蓋 web.config.comments 文件中的所有設置。請確保該節點位於配置文件中的 <system.web> 節點之間。

使用驗證控件限制上傳類型

 

<ASP:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<ASP:Button ID="Button1" runat="server" OnClick="Button1_Click" 
Text
="Upload File" /> <br />
<br />
<ASP:Label ID="Label1" runat="server"></ASP:Label>
<ASP:RegularExpressionValidator 
id
="RegularExpressionValidator1" runat="server" 
ErrorMessage
="Only mp3, m3u or mpeg files are allowed!" 
ValidationExpression
="^(([a-zA-Z]:)|(/{2}w+)$?)(/(w[w].*))
    +(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$" 
ControlToValidate="FileUpload1"></ASP:RegularExpressionValidator>
<br />
<ASP:RequiredFieldValidator 
id
="RequiredFieldValidator1" runat="server" 
ErrorMessage
="This is a required field!" 
ControlToValidate
="FileUpload1"></ASP:RequiredFieldValidator>

Protected Sub Button1_Click(ByVal sender As Object, _
      
ByVal e As System.EventArgs)
        
If FileUpload1.HasFile Then
            
Dim fileExt As String
            fileExt 
= System.IO.Path.GetExtension(FileUpload1.FileName)
            
            
If (fileExt = ".mp3"Then
                
Try
                    FileUpload1.SaveAs(
"C:Uploads" & _
                       FileUpload1.FileName)
                    Label1.Text 
= "File name: " & _
                      FileUpload1.PostedFile.FileName 
& "" & _
                      
"File Size: " & _
                      FileUpload1.PostedFile.ContentLength 
& " kb" & _
                      
"Content type: " & _
                      FileUpload1.PostedFile.ContentType
                
Catch ex As Exception
                    Label1.Text 
= "ERROR: " & ex.Message.ToString()
                
End Try
            
Else
                Label1.Text 
= "Only .mp3 files allowed!"
            
End If
        
Else
            Label1.Text 
= "You have not specified a file."
        
End If
    
End Sub


 

檢查服務器上的文件類型(C#)

    
protected void Button1_Click(object sender, EventArgs e)
    
{

        
if (FileUpload1.HasFile)
        
{
            
string fileExt = 
               System.IO.Path.GetExtension(FileUpload1.FileName);

            
if (fileExt == ".mp3")
            
{
                
try
                
{
                    FileUpload1.SaveAs(
"C:/Uploads/" + 
                       FileUpload1.FileName);
                    Label1.Text 
= "File name: " +
                        FileUpload1.PostedFile.FileName 
+ "" +
                        FileUpload1.PostedFile.ContentLength 
+ " kb" +
                        
"Content type: " +
                        FileUpload1.PostedFile.ContentType;
                }

                
catch (Exception ex)
                
{
                    Label1.Text 
= "ERROR: " + ex.Message.ToString();
                }

            }

            
else
            
{
                Label1.Text 
= "Only .mp3 files allowed!";
            }

        }

        
else
        
{
            Label1.Text 
= "You have not specified a file.";
        }

    }

同時上載多個文件

C#

protected void Button1_Click(object sender, EventArgs e)
{
   
string filepath = "C:/Uploads";
   
//HttpFileCollection類型   HttpFileCollection uploadedFiles = Request.Files;
    
   
for (int i = 0; i < uploadedFiles.Count; i++)
   
{    
      
//HttpPostedFile類型      HttpPostedFile userPostedFile = uploadedFiles[i];
    
      
try
      
{    
         
if (userPostedFile.ContentLength > 0 )
         
{
            Label1.Text 
+= "File #" + (i+1+ 
               
"";
            Label1.Text 
+= "File Content Type: " + 
               userPostedFile.ContentType 
+ "";
            Label1.Text 
+= "File Size: " + 
               userPostedFile.ContentLength 
+ "kb";
            Label1.Text 
+= "File Name: " + 
               userPostedFile.FileName 
+ "";
    
            userPostedFile.SaveAs(filepath 
+ "/" + 
               System.IO.Path.GetFileName(userPostedFile.FileName));
    
            Label1.Text 
+= "Location where saved: " + 
               filepath 
+ "/" + 
               System.IO.Path.GetFileName(userPostedFile.FileName) 
+ 
               
"
"
;
         }
    
      }
 
      
catch (Exception Ex)
      
{    
         Label1.Text 
+= "Error: " + Ex.Message;    
      }
    
   }
    
}


圖 5. 一次將一個 ASP.NET 頁上的三個文件上載到服務器


最後:此法缺少文件狀態 有待改進!
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章