话不多说,直接上代码
页面部分
<form id="form1" enctype="multipart/form-data">
id_token: <input type="text" id="id_token" value="qweasd123">
文件:<input type="file" id="file" name="imgfile">
<input type="button" onclick="upload()" value="上传">
</form>
js部分
function upload() {
var formData = new FormData();
var file = document.getElementById('file').files[0];
var id_token = $('#id_token').val();
formData.append("file", file);
formData.append("id_token", id_token);
$.ajax({
url: "/ajax/upload",
type: "post",
data: formData,
dataType: "json",
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须*/
success: function (data) {
console.log(data.file);
console.log(data.id_token);
}
});
}
后台接收部分
@ResponseBody
@RequestMapping(value = "/ajax/upload",method = RequestMethod.POST)
public String upload(MultipartFile file,String id_token) {
JSONObject json = new JSONObject();
try {
System.out.println(file.getOriginalFilename());
System.out.println(id_token);
json.put("file", file.getOriginalFilename());
json.put("id_token", id_token);
} catch (Exception e) {
logger.error("AjaxImgController.upload error:", e);
}
return json.toString();
}
结果
![](https://img2018.cnblogs.com/blog/1420848/201811/1420848-20181121112320747-685252521.png)
注意部分
<!--文件上传设置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>