<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--指定文件的編碼-->
<property name="defaultEncoding" value="utf-8"></property>
<!--指定上傳文件的最大大小-->
<property name="maxUploadSize" value="1024000"></property>
</bean>
- 若是設置了文件的最大限制,則須要在配置文件中添加以下代碼,來指定超出限制時所跳轉的錯誤頁面:
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error</prop>
</props>
</property>
</bean>
<%-- Created by IntelliJ IDEA. User: elin Date: 15-7-4 Time: 下午7:28 To change this template use File | Settings | File Templates. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<form action="<%=request.getContextPath()%>/user/uploadHandle" method="post" enctype="multipart/form-data">
描述:<input type="text" name="desc">
上傳文件:<input type="file" name="file" multiple="multiple">
<input type="submit" value="上傳">
</form>
</body>
</html>
@RequestMapping("/uploadHandle")
public String uploadHandle(@RequestParam("desc") String desc,@RequestParam("file") MultipartFile[] multipartFiles) throws Exception{
// 遍歷數組中的多個文件,示例jsp頁面爲只上傳一個文件
for (MultipartFile multipartFile : multipartFiles) {
String path = "/home/elin/workspace/upload/";
// 獲取原始圖片名稱
String oldFileName = multipartFile.getOriginalFilename();
// 設置隨機的圖片名稱
String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
// 建立新的文件
File file = new File(path + newFileName);
// 把內存中的圖片寫入對應的目錄
multipartFile.transferTo(file);
}
return "success";
}