SpringBoot需要引用Apache Commons FileUpload组件依赖,在pom.xml配置
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
文件上传参数配置application.properties:
单文件最大50MB
spring.servlet.multipart.max-file-size=50MB
整个请求大小最大500MB,换言之就是上传多个文件总大小不超过500MB
spring.servlet.multipart.max-request-size=500MB
文件上传:
html:
<h1>表单提交</h1>
<form action="upload" enctype="multipart/form-data" method="post">
文件描述:<input type="text" name="context" ><br>
文件:<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
Controller:
@RequestMapping("/upload")
public String upload(HttpServletRequest request, @RequestParam("context") String context, @RequestParam("file")MultipartFile file){
System.out.println("文件描述:"+context);
if(!file.isEmpty()){
String path="D:/Test";
String filename=file.getOriginalFilename();
File filepath=new File(path+File.separator+filename);
if(!filepath.getParentFile().exists())filepath.getParentFile().mkdirs();
System.out.println(filepath.getAbsolutePath());
try {
file.transferTo(filepath);
} catch (IOException e) {
e.printStackTrace();
}
}
/****** 以上代码已将上传的文件放入到path中 ,这里返回展示已上传文件的页面 ******/
return "forward:/showDownLoad";
}
设置下载页面:
Controller:
//将文件列表显示出来
@RequestMapping("/showDownLoad")
public String showDownLoad(HttpServletRequest request, Model model){
String path="D:/Test";
File filedir=new File(path);
File[] fileList=filedir.listFiles();
model.addAttribute("filesList",fileList);
return "index";
}
//以流的方式将文件输出
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpServletRequest request,@RequestParam("filename") String filename,@RequestHeader("User-Agent") String userAgent){
String path="D:/Test";
File downfile=new File(path+File.separator+filename);
ResponseEntity.BodyBuilder builder=ResponseEntity.ok();
builder.contentLength(downfile.length());
builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
try {
filename= URLEncoder.encode(filename,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(userAgent.indexOf("MSIE")>0){
builder.header("Content-Disposition","attachment;filename="+filename);
}else{
builder.header("Content-Disposition","attachment;filename*=UTF-8''"+filename);
}
try {
return builder.body(FileUtils.readFileToByteArray(downfile));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
html:这里用了Thymeleaf模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr th:each="file,stat:${filesList}">
<td><span th:text="${stat.count}"></span></td>
<td><a th:href="@{download(filename=${file.name})}" ><span th:text="${file.name}"></span></a></td>
</tr>
</table>
</body>
</html>
这里的
<td><a th:href="@{download(filename=${file.name})}" ><span th:text="${file.name}">
会被加载成,例:
<td><a href="download?filename=2017.jpg"><span>2017.jpg</span></a></td>