前言
- 做項目時,遇到表單中圖像需要跟表單一起送出,這樣會造成背景沒辦法接收到圖檔。後面上網調查後,明白表單送出時是預設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> 3, 153, 153);">1
2 3 4 5 <%@ 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";
}
後語
- 該實作并不難,主要了解表單送出格式和相關實作即可。希望可以幫到相關人員。