ASP.NET MVC上传文件的方法

原文链接点击打开链接

1.Form表单提交


1
2
3
4
5
<p>Form提交</p>
<form action= "@Url.Action(" SavePictureByForm ")"  enctype= "multipart/form-data"  method= "post" >
     <input id= "pic"  name= "pic"  type= "file"  />
     <input type= "submit"  value= "提交"  />
</form>

2.Ajax.BeginForm,原理也是Form表单提交

1
2
3
4
5
6
<p>Ajax.BeginForm</p>
@using(Ajax.BeginForm( "SavePictureByForm" null new  AjaxOptions() { OnSuccess =  "PostSuc" , OnFailure =  "PostFail" , HttpMethod =  "Post" },  new  {enctype =  "multipart/form-data" }))
{
    <input type= "file"  name= "pic"  id= "pic"  multiple= "multiple"  />
    <input type= "submit"  value= "提交"  />
}

以上两种方式,在后台用同一种方法可以获取数据: 但是这两种方法会造成页面刷新,有时会影响用户操作.

1
2
3
4
5
6
7
8
9
10
11
public  ActionResult SavePictureByForm()
        {
            HttpFileCollectionBase files = Request.Files;
            var  file = files[0];
            bool  isOk =  false ;
            string  msg =  string .Empty;
            //....OtherDO
 
 
            return  Content( "<script>window.location.href='/home/index';</script>" );
        }

3.Ajax提交  用此方法需要用到FileReader类,再获取到文件的Base64数据,将Base64数据Post过去

1
2
3
4
<p>Ajax:以上传图片为例</p>
<input type= "file"  id= "picAjax" />
<input type= "button"  id= "submitPic"  value= "提交"  />
<img id= "selImg"   src= ""  alt= "用作图片预览"  />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var  picString =  "" ;
$( function  () {
     $( "#picAjax" ).change( function  (e) {
         var  file = e.delegateTarget.files[0];
         //在此可以对选择的文件进行判断:文件类型 文件大小等
         //.....
         
         var  reader =  new  FileReader();
         reader.readAsDataURL(file);
         reader.onload =  function  (ret) {
             picString = reader.result
             //预览图片
             $( "#selImg" ).attr({  "src" : picString });
         }
     });
 
     $( "#submitPic" ).click( function  () {
         $.ajax( "home/SavePicture" , {
             type:  "post" ,
             datatype:  "json" ,
             data: picString,
             error:  function  () { },
             success:  function  (result) {
                 if  (result) {
                     alert(result.msg);
                 }
             }
         });
     });

后端接收

1
2
3
4
5
6
7
8
9
10
[HttpPost]
        public  ActionResult SavePicture( string  picString)
        {
            bool  isOk =  false ;
            string  msg =  string .Empty;
            //其他操作
            //.........
            //.........
            return  Json( new  { suc = isOk, msg = msg });
        }

第三种方法做到了真正异步提交.但是如果选择的文件较大,可能会出现问题(未测试).

 

对于图片预览 前两种方法也可用base64数据进行图片预览.




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值