SpringMVC文件上傳
1.pom.xml導入jar
<!-- 本地文件上傳 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 跨服務器上傳 -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.10</version>
</dependency>
2.springContext.xml配置CommonsMultipartResolver
<!-- 文件上傳配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上傳文件的編碼 -->
<property name="defaultEncoding" value="UTF-8" />
<!--上傳文件的最大大小,單位爲字節 -->
<property name="maxUploadSize" value="10000000" />
</bean>
3.前端jsp頁面
- input的type設置爲file
- form表單的method設爲post
- form表單的enctype設置爲multipart/form-data,序列化以二進制的形式傳輸數據
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<h2>Hello World!</h2>
<form action="fileload.do" method="post" enctype="multipart/form-data">
<input type="file" name="upload" />
<input type="submit" value="上傳" />
</form>
<br> ${msg}
</body>
</html>
4.Handler接收處理
@RequestMapping("/fileload")
public String fileUpLoad(HttpServletRequest request, MultipartFile upload) throws Exception {
String path = "D://upload";
File f = new File(path);
if (!f.exists()) {
f.mkdir();
}
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
String name = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
if (name.endsWith(".jpg")||name.endsWith(".png")) {
upload.transferTo(new File(path, name));
request.setAttribute("msg", "上傳成功");
return "forward:index.jsp";
}else {
request.setAttribute("msg", "上傳失敗");
return "forward:index.jsp";
}
}
@RequestMapping("/fileloadtest")
public String fileUpLoad01(HttpServletRequest request, MultipartFile upload) throws Exception {
String path = "http://localhost:8888/uploads/";
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
String name = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
Client client = Client.create();
WebResource webResource = client.resource(path + filename);
webResource.put(upload.getBytes());
return "success";
}