2010-01-04 41 views
5

我正在使用<input type="file" />標記將文件上傳到服務器。我如何在服務器端訪問文件並將其存儲在服務器上? (該文件是圖像文件)訪問asp.net中服務器端的輸入類型文件

客戶端側的代碼是:

<form id="form1" action="PhotoStore.aspx" enctype="multipart/form-data"> 
    <div> 
    <input type="file" id="file" onchange="preview(this)" /> 
    <input type="submit" /> 
    </div> 
</form> 

Photostore.aspx.cs具有

protected void Page_Load(object sender, EventArgs e) 
     { 
      int index = 1; 
      foreach (HttpPostedFile postedFile in Request.Files) 
      { 
       int contentLength = postedFile.ContentLength; 
       string contentType = postedFile.ContentType; 
       string fileName = postedFile.FileName; 

       postedFile.SaveAs(@"c:\test\file" + index + ".tmp"); 

       index++; 
      } 

     } 

我試圖上載jpg文件。無法看到保存的文件。出了什麼問題?

+0

winforms或mvc或其他? – 2010-01-04 09:42:39

回答

0

查看ASP.NET提供的asp:FileUpload控件。

6

你需要添加idrunat="server"屬性是這樣的:

<input type="file" id="MyFileUpload" runat="server" /> 

然後,在服務器端,你將有機會獲得該控件的屬性PostedFile,它會給你ContentLengthContentTypeFileNameInputStream屬性和方法SaveAs等:

int contentLength = MyFileUpload.PostedFile.ContentLength; 
string contentType = MyFileUpload.PostedFile.ContentType; 
string fileName = MyFileUpload.PostedFile.FileName; 

MyFileUpload.PostedFile.Save(@"c:\test.tmp"); 

或者,你可以使用Request.Files WH ICH給你所有上傳文件的集合:

int index = 1; 
foreach (HttpPostedFile postedFile in Request.Files) 
{ 
    int contentLength = postedFile.ContentLength; 
    string contentType = postedFile.ContentType; 
    string fileName = postedFile.FileName; 

    postedFile.Save(@"c:\test" + index + ".tmp"); 

    index++; 
} 
+0

爲什麼runat =「server」?我不想要一個服務器控件。這將工作沒有服務器控制? – Ajay 2010-01-04 09:53:04

+3

如果你不想使用服務器控件,那麼你可以使用'Request.Files',它會給你一個包含每個上傳文件的'HttpPostedFile'對象的集合。 – LukeH 2010-01-04 09:57:56

+0

非常感謝你@LukeH ...你讓我擺脫了麻煩...... :) – 2012-09-14 11:06:14

0

如果你給輸入標籤的ID,並添加RUNAT =「server」屬性,那麼你可以很容易地訪問它。
首先改變你的輸入標籤:<input type="file" id="FileUpload" runat="server" />
然後將以下添加到您的Page_Load方法:

if (FileUpload.PostedFile != null) 
{ 
    FileUpload.PostedFile.SaveAs(@"some path here"); 
} 

這將你的文件寫入到您選擇的文件夾。如果需要確定文件類型或原始文件名,則可以訪問PostedFile對象。

2

我覺得這個名字標籤必須在文件輸入:

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

沒有這一點,我沒有得到任何回報。


我有,這可能是我機器上的另一些問題:

我在該行

foreach (HttpPostedFile postedFile in Request.Files) 

所以我最終的代碼看起來得到

Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'. 

錯誤像這樣:

for (var i = 0; i < Request.Files.Count; i++) 
{ 
    var postedFile = Request.Files[i]; 

    // do something with file here 
} 
相關問題