springMVC实现文件上传和下载:
一、下载
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<a th:href="@{/download}">下载</a>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
图片:<input type="file" name="photo">
<input type="submit" value="上传">
</form>
</body>
</html>
controller.java
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpSession session) throws Exception {
ServletContext context = session.getServletContext();
String realPath = context.getRealPath("/static/js/vue.js");
InputStream is = new FileInputStream(realPath);
byte[] bytes = new byte[is.available()];
is.read(bytes);
MultiValueMap<String,String> headers = new HttpHeaders();
headers.add("Content-Disposition","attachment;filename=v.js");
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status);
is.close();
return responseEntity;
}
二、上传
依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
springmvc.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
controller.java
@RequestMapping("/upload")
public String upload(MultipartFile photo,HttpSession session) throws IOException {
//获取上传文件名
String filename = photo.getOriginalFilename();
String hzname = filename.substring(filename.lastIndexOf("."));
filename = UUID.randomUUID().toString()+hzname;
ServletContext servletContext = session.getServletContext();
String photopath = servletContext.getRealPath("photo");
File file = new File(photopath);
if (!file.exists()){
file.mkdir();
}
String finalpath = photopath+File.separator+filename;
photo.transferTo(new File(finalpath));
return "test";
}