前言
- 做项目时,遇到表单中图像需要跟表单一起提交,这样会造成后台没办法接收到图片。后面上网调查后,明白表单提交时是默认application/x-www-form-urlencoded格式,只接受键值对。所以以下例子采用FormData格式异步提交表单,因为formData格式可以接收文件格式。
具体流程
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="4096"/>
</bean>
3, 153, 153);">1
2345
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<body>
<h1>使用formData形式上传文件</h1>
<form id="uploadForm" method="post" action="/upload.ajax" >
<input type="file" id="avatar" name="avatar" onchange="previewImage('preview',this)" >
<img id="preview">
<button id="submit" type="button">提交</button>
</form>
</body>
</html>
<script src="/media/js/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function previewImage(preImageId, imageFile) {
var pattern = /(\.*.jpg$)|(\.*.png$)|(\.*.jpeg$)|(\.*.gif$)|(\.*.bmp$)/;
if (!pattern.test(imageFile.value)) {
alert("系统仅支持jpg/jpeg/png/gif/bmp格式的照片!");
imageFile.focus();
$(imageFile).val("");
return false;
} else {
var path;
if (document.all)
{
imageFile.select();
path = document.selection.createRange().text;
}
else
{
path = URL.createObjectURL(imageFile.files[0]);
}
$('#' + preImageId).attr('src', path);
}
}
$('#submit').on('click',function () {
var formData = new FormData($( "#uploadForm" )[0]);
console.log(formData);
$.ajax({
type: 'POST',
url: '/upload.ajax',
data: formData,
contentType: false,
processData: false,
success: function (result) {
console.log(result);
},
});
});
</script>
@RequestMapping("upload.ajax")
@ResponseBody
public String upload(MultipartFile avatar){
return "success";
}
后语
- 该实现并不难,主要了解表单提交格式和相关实现即可。希望可以帮到相关人员。