[转]Asp.NET MVC3 + Ajax 实现多文件上传

时间:2022-11-28 19:05:44

本文转自:http://hi.baidu.com/softworm/item/ed0aa753df00373094eb05cf

HTML

1
2
3
4
5
6
< form id = "form1" name = "form1" >
         < input type = "file" name = "fileToUpload" id = "fileToUpload"  multiple = "multiple"  />
         < progress id = "progressBar" value = "0" max = "100" ></ progress >
         < span id = "percentage" ></ span >
         < input type = "button" onclick = "UpladFile()" value = "Upload" />
</ form >

JS

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
30
31
32
33
34
35
<script type= "text/javascript" >
    function UpladFile() {
        // js 获取文件对象
        var fileObj = document.getElementById( "fileToUpload2" ).files;
        // 接收上传文件的后台地址
        var FileController = "/Home/Upload" ;                   
   
        // FormData 对象
        var form = new FormData();
        // 可以增加表单数据
        form.append( "author" , "hooyes" );
        // 文件对象                      
        for ( var i = 0; i < fileObj.length; i++)                
            form.append( "file" + i, fileObj[i]);
   
        // XMLHttpRequest 对象
        var xhr = new XMLHttpRequest();
        xhr.open( "post" , FileController, true );
        xhr.onload = function () {
            alert( "上传完成!" );
        };
        xhr.upload.addEventListener( "progress" , progressFunction, false );
        xhr.send(form);
    }
   
    function progressFunction(evt) {
        var progressBar = document.getElementById( "progressBar" );
        var percentageDiv = document.getElementById( "percentage" );
        if (evt.lengthComputable) {
            progressBar.max = evt.total;
            progressBar.value = evt.loaded;
            percentageDiv.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%" ;
        }
   
   </script>

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
[HttpPost]
        public ActionResult Upload()
        {
            HttpFileCollectionBase fileToUpload = Request.Files;
            foreach ( string file in fileToUpload)
            {
                var curFile = Request.Files[file];
                if (curFile.ContentLength < 1) continue ;
                string path = System.IO.Path.Combine(Server.MapPath( "~/Upload" ), System.IO.Path.GetFileName(curFile.FileName));
                curFile.SaveAs(path);
            }
            return RedirectToAction( "Index" );
        }

jQuery

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
30
31
32
33
34
<script type= "text/javascript" >
    $(document).ready( function () {
        $( '#form1' ).submit( function () {
            var formdata = new FormData();
            var fileObj = document.getElementById( "fileToUpload2" ).files;
            for ( var i = 0; i < fileObj.length; i++)
                formdata.append( "file" + i, fileObj[i]);
            $.ajax({
                type: 'POST' ,
                url: '/Home/Upload2' ,
                data: formdata,
                /**
                *必须false才会自动加上正确的Content-Type
                */
                contentType: false ,
                /**
                * 必须false才会避开jQuery对 formdata 的默认处理
                * XMLHttpRequest会对 formdata 进行正确的处理
                */
                processData: false
            }).then( function () {
                alert( 'done' );
            }, function () {
                //failCal
            });
            return false ;
        });
        $( "#btn" ).bind( "click" , ajaxUpload);
    });
 
    function ajaxUpload() {
        $( "#form1" ).submit();
    }
</script>