Ajax实现文件上传

jopen 7年前

    <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>  
    <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;                     });                     });                function ajaxUpload() {                     $("#form1").submit();             }         </script>