ASP.net MVC FileUpload 文件上传

本文介绍了如何在ASP.NET MVC项目中实现文件上传功能。通过创建上传表单并使用HTML Helper编写,配合相应的Action处理文件的接收与保存,最终实现了文件上传流程。

原文地址: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(); 
        } 
    } 
} 
 
保存后直接运行


 
这样就可以测试了。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值