我们常用的文件上传都是用form表单的file。普通的ajax只能上传一般的form表单,不能上传文件。
要想使用ajax实现文件上传,需要使用FormData对象发送.
https://developer.mozilla.org/zh-CN/docs/Web/Guide/Using_FormData_Objects
页面:
<form id="import_form" name="fileName" enctype="multipart/form-data"> <input type="file" name="file" size="50"> <button type="button" οnclick="wordsSetting.upLoad()" class="btn btn-sm blue-madison"> 导入 </button> <button type="button" οnclick="wordsSetting.cancelUpLoad()" class="btn btn-sm ml10 default"> 取消导入 </button> </form>
js:
var oData = new FormData(document.forms.namedItem("fileName")); $.ajax({ url:contextPath+"/system_setting/words/upLoad.json", type: 'post', dataType: 'json', data: oData, processData:false, contentType:false, success: function (data) { var upLoadContent=data.upLoadContent; $("#inWords").text(upLoadContent); wordsSetting.cancelUpLoad(); }, error: function (data) { var message = eval('(' + data.responseText + ')'); alert("导入失败") } });
spring的配置中配置文件上传:
<!--文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <property name="maxUploadSize" value="10000"/> </bean>
controller中使用文件类型接收:
接收参数: MultipartFile file