ASP.net MVC FileUpload 文件上传

ASP.net MVC的上传文件功能并没有其他模块(action,Controller)那么智能、好用,不过也不是很复杂。

打开vs2008 新建一个MVC工程

image

如果web项目没有asp.net mvc web application的话,请下载 .net MVC

确定后显示Unit Test选项 根据需要选择,这里就选择NO。

image

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

image

用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,打开

image 

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 ( ) ;
                }
        }
}
保存后直接运行
image
 

这样就可以测试了。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值