欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET MVC处理文件上传的小例子

程序员文章站 2024-02-29 17:04:58
复制代码 代码如下:

复制代码 代码如下:

<asp:content id="content2" contentplaceholderid="maincontent" runat="server">   
 
<h2>files uploaded to server</h2>   
 
<div id="dialog" title="upload files">     
  <% using (html.beginform("upload", "file", formmethod.post, new 

{ 

enctype = "multipart/form-data" 

}

)) 
  {%>

<br /> 
    <p><input type="file" id="fileupload" name="fileupload" size="23"/> ;</p><br /> 
    <p><input type="submit" value="upload file" /></p>     
  <% } %>   
</div> 
<a href="#" onclick="jquery('#dialog').dialog('open'); return false">upload file</a> 
</asp:content> 


然后,我们需要根据beginform中filecontroller和action(upload)在指定的controller中处理请求,参考如下代码:
复制代码 代码如下:

public void upload( 
{ 
foreach (string inputtagname in request.files) 
{ 
httppostedfilebase file = request.files[inputtagname]; 
if (file.contentlength > 0) 
{ 
string filepath = path.combine(httpcontext.server.mappath("../uploads") 
, path.getfilename(file.filename)); 
file.saveas(filepath); 
} 
} 
 
redirecttoaction("index", "file"); 
}