2010-01-04 43 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 
} 
相关问题