前言
- 作項目時,遇到表單中圖像須要跟表單一塊兒提交,這樣會形成後臺沒辦法接收到圖片。後面上網調查後,明白表單提交時是默認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>
<!--multipart處理類-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="4096"/>
</bean>
<%@ 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)//IE
{
imageFile.select();
path = document.selection.createRange().text;
}
else//FF
{
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){
//處理avatar邏輯
return "success";
}
後語
- 該實現並不難,主要了解表單提交格式和相關實現便可。但願能夠幫到相關人員。