使用FormData,进行Ajax请求并上传文件
这里使用JQuery,但是老版本的JQuery比如1.2是不支持的,最好使用2.0或更新版本:
注:
如上,通过$('#postForm').serialize()可以对form表单进行序列化,从而将form表单中的所有参数传递到服务端。
但是上述方式,只能传递一般的参数,上传文件的文件流是无法被序列化并传递的。
不过如今主流浏览器都开始支持一个叫做FormData的对象,有了这个FormData,我们就可以轻松地使用Ajax方式进行文件上传了。
- <div class="modal fade bs-example-modal-sm1" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm1">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel2">机器信息导入</h4>
</div>
<div class="modal-body">
<form id="excelImportForm">
<table class="table table-striped table-bordered dataTable no-footer">
<tbody>
<tr>
<td style="text-align: center;font-size:20px;font-weight:700">文件</td>
<td><input type="file" name="fileName"/></td>
<td><input type="hidden" name="type" value="machInfo"/></td>
</tr>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="cancelId">取消</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" οnclick="machInfoImport()">导入</button>
</div>
</div>
</div>
</div>
-
function machInfoImport(){ var formData= new FormData($("#excelImportForm")[0]); $.ajax({ type:'POST', url:'/fudaMes/excel/importExcel', data:formData, async: false, cache: false, contentType: false, processData: false, //必须要 success: function (data) { if(data=="success"){ new PNotify({ title:'导入成功', text: '机器信息导入成功', type: 'success', styling: 'bootstrap3' }); }else{ new PNotify({ title:'导入失败', text: ''+data, type: 'error', styling: 'bootstrap3' }); } $(".modal-backdrop").remove(); $("body").removeClass('modal-open'); $('body').removeAttr("style") $('body').css('display','block'); load_orderInfo(); }, error: function (data) { console.log(JSON.stringify(data)) } }); }