依賴與配置
- 前端:jQuery + ajaxfileupload.js
- 後端:
commons-fileupload、commons-io
- Spring 配置
CommonsMultipartResolver 限制大小 800KB
1. Spring 配置 applicationContext.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="800000"/>
</bean>
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
</props>
</property>
</bean>
2. 前端頁面 index.jsp
<script src="${pageContext.request.contextPath}/js/jquery-1.10.2.min.js"></script>
<script src="${pageContext.request.contextPath}/js/ajaxfileupload.js"></script>
<script>
function ajaxFileUpload() {
$.ajaxFileUpload({
url: '${pageContext.request.contextPath}/test/fileUpload?uname=玄玉',
secureuri: false,
fileElementId: 'myBlogImage', // <input type="file" id="myBlogImage">
dataType: 'text',
success: function(data) {
data = data.replace(/<?pre>/gi, ''); // 移除插件添加的 pre 標籤
if (data.startsWith("0")) {
$("#uploadImage").attr("src", data.substring(2));
$("#result").html("圖片上傳成功");
} else {
$("#result").html("上傳失敗:" + data.substring(2));
}
},
error: function() { $("#result").html("上傳異常"); }
});
}
</script>
<input type="file" id="myBlogImage" name="myfiles"/>
<input type="button" value="上傳圖片" onclick="ajaxFileUpload()"/>
<img id="uploadImage" src="default.png"/>
<div id="result"></div>
3. Controller 處理
@Controller
@RequestMapping("/test")
public class FileUploadController {
@RequestMapping("/fileUpload")
@ResponseBody
public void upload(@RequestParam("uname") String uname,
@RequestParam MultipartFile[] myfiles,
HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain; charset=UTF-8");
PrintWriter out = resp.getWriter();
String realPath = req.getSession().getServletContext().getRealPath("/upload");
for (MultipartFile f : myfiles) {
if (f.isEmpty()) { out.print("1`請選擇文件"); return; }
FileUtils.copyInputStreamToFile(f.getInputStream(), new File(realPath, f.getOriginalFilename()));
}
// 返回協議:0`相對路徑
out.print("0`" + req.getContextPath() + "/upload/" + myfiles[0].getOriginalFilename());
}
}
常見錯誤代碼對照
| JS 錯誤 | 原因 |
| SyntaxError: missing ; before statement | URL 路徑錯誤 |
| SyntaxError: invalid property id | fileElementId 不存在 |
| SyntaxError: missing } in XML expression | 文件域 name 不匹配 |