2011-03-29 108 views

回答

1

使用FileUpload control

例如(從鏈接的MSDN文章修改),如果你只是想要一個簡單的表格,上傳文件到服務器上的路徑,你可以像這樣開始:

<%@ Page Language="C#" %> 

<script runat="server"> 
    protected void UploadFileAction_Click(object sender, EventArgs e) 
    { 
     var fileStoragePath = Server.MapPath("~/Uploads"); 

     if (fileUploader.HasFile) 
     { 
      fileUploader.SaveAs(Path.Combine(fileStoragePath, fileUploader.FileName)); 
      outputLabel.Text = string.Format(
       "File Name: {0}<br />File Size: {1}kb<br />Content Type: {2}", 
       fileUploader.PostedFile.FileName, 
       fileUploader.PostedFile.ContentLength, 
       fileUploader.PostedFile.ContentType 
      ); 
     } 
     else 
      outputLabel.Text = "You have not specified a file."; 
    } 
</script> 

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
    <title>Upload A File</title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <asp:FileUpload ID="fileUploader" runat="server" /><br /> 
     <br /> 
     <asp:Button ID="uploadFileAction" runat="server" OnClick="UploadFileAction_Click" Text="Upload File" />&nbsp;<br /> 
     <br /> 
     <asp:Label ID="outputLabel" runat="server"></asp:Label></div> 
    </form> 
</body> 
</html> 

FileUpload作爲整體ASP.NET表單元素管理的一部分,與其他服務器端表單控件一樣,控制最終會在客戶端上呈現爲簡單的<input type="file" />(但具有更多的屬性集)。

在你的問題中,你特別提到了上傳一個「圖片」。雖然這段代碼可能會讓你在那裏,但你也可能會隱含地詢問第二個問題:「我如何確保上傳的文件是圖像?」如果是這樣,您在this question以及this one(其中提到更多關於其他問題的答案,這是一個熱門話題)的回答中列出了幾個選項。與往常一樣,儘管客戶端驗證仍然建議用於良好的用戶體驗,但服務器端驗證仍然是必需的。永遠不要隱式信任客戶端驗證,並始終驗證服務器上的用戶輸入。

+0

雖然這個鏈接可能回答這個問題,但最好在這裏包括答案的重要部分,並提供請參閱鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – Rob 2012-11-17 10:58:56

+0

@Rob:謝謝你的提醒。這是我從未回過頭和更新過的一個較老的謎題答案。固定。 – David 2012-11-17 12:00:24

+0

+1全面解答! =) – Rob 2012-11-17 12:33:59

1

下面是代碼示例:

你的HTML:

<input type="file" name="Pic_0001"> 

注意:HTML輸入控制必須位於表單內

現在你的ASP .NET代碼:

'this is your file name at html page 
    Dim HtmlFilename As String = "Pic_0001" 

    'the place to manipulate all uploaded files 
    Dim collection As System.Web.HttpFileCollection 
    collection = Page.Request.Files 

    'for example, you have selected a picture file named hotdog.jpg in browser 
    'this variable will manipulate your hotdog.jpg file 
    Dim UploadedFile As System.Web.HttpPostedFile 

    'retrieve the reference to your file 
    UploadedFile = collection.Item(HtmlFilename) 

    'this is the location to save your uploaded file 
    Dim WhereToSave As String = "c:\test folder\hotdog.jpg" 

    'this is your folder that will contain the uploaded file 
    Dim Folderpath As String = System.IO.Path.GetDirectoryName(WhereToSave) 

    'now do checking if the folder exists, if not create the folder 
    'NOTE: this step is needed to prevent folder not exists error 
    If System.IO.Directory.Exists(Folderpath) = False Then 
     System.IO.Directory.CreateDirectory(Folderpath) 
    End If 

    'now actually save your file to the server 
    UploadedFile.SaveAs(WhereToSave)