ASP.net MVC FileUpload 文件上传

Posted by 李小武 on April 6, 2010

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(); 
        } 
    } 
} 

  保存后直接运行。