原文地址:http://blog.lichengwu.cn/c-sharp/2010/04/06/ASP.net-MVC-FileUpload/
ASP.net MVC的上传文件功能并没有其他模块(action,Controller)那么智能、好用,不过也不是很复杂。
打开vs2008 新建一个MVC工程

如果web项目没有asp.net mvc web application的话,请下载 .net MVC
确定后显示Unit Test选项 根据需要选择,这里就选择NO。

首先建立我们上传文件的form,打开

用HTML helper编写一个form,当然也可以用纯HTML
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>File Upload Example</h2>
<p>
File 1:<input type="file" name="file1" id="file1" /><br />
<input type="submit" id="upload" value="Upload" />
</p>
</asp:Content>
然后编写相应的action,打开

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.IO;
namespace FileUpload.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
//ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult Upload()
{
StringBuilder info = new StringBuilder();
foreach (string file in Request.Files)
{
HttpPostedFileBase postFile = Request.Files[file];//get post file
if (postFile.ContentLength == 0)
continue;
string newFilePath = @"D:/";//save path
postFile.SaveAs(newFilePath + Path.GetFileName(postFile.FileName));//save file
info.AppendFormat("Upload File:{0}/r/n", postFile.FileName);//info
}
ViewData["Info"] = info;
return View("Index");
}
public ActionResult About()
{
return View();
}
}
}
保存后直接运行
这样就可以测试了。
本文介绍了如何在ASP.NET MVC项目中实现文件上传功能。通过创建上传表单并使用HTML Helper编写,配合相应的Action处理文件的接收与保存,最终实现了文件上传流程。
918

被折叠的 条评论
为什么被折叠?



