在这里我用两种实现方式
第一种
- pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- application.properties
spring.thymeleaf.cache=true
- html
file.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form action="fileUpload" method="post" enctype="multipart/form-data">
<p>选择文件: <input type="file" name="fileName"/></p>
<p><input type="submit" value="提交"/></p>
</form>
</body>
</html>
multifile.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head> <meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form action="multifileUpload" method="post" enctype="multipart/form-data" >
<p>选择文件1: <input type="file" name="fileName"/></p>
<p>选择文件2: <input type="file" name="fileName"/></p>
<p>选择文件3: <input type="file" name="fileName"/></p>
<p><input type="submit" value="提交"/></p>
</form>
</body>
</html>
- controller
package com.spring.boot.upload.Controller;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class UploadController {
@GetMapping("/file")
public String file() {
return "file";
}
/*
* 实现文件上传
*/
@RequestMapping("fileUpload")
@ResponseBody
public String fileUpload(@RequestParam("fileName") MultipartFile file) {
if (file.isEmpty()) {
return "false";
}
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
String path = "C:\\upload";
File dest = new File(path + "/" + fileName);
if (!dest.getParentFile().exists()) {
// 判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest); // 保存文件
return "true";
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
/*
* 获取multifile.html页面
*/
@RequestMapping("multifile")
public String multifile() {
return "/multifile";
}
/*
* 实现多文件上传
*/
@RequestMapping(value = "multifileUpload", method = RequestMethod.POST)
/**
* public @ResponseBody String
* multifileUpload(@RequestParam("fileName")List<MultipartFile> files)
*/
public @ResponseBody String multifileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");
if (files.isEmpty()) {
return "false";
}
String path = "C:\\upload";
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
if (file.isEmpty()) {
return "false";
} else {
File dest = new File(path + "/" + fileName);
if (!dest.getParentFile().exists()) {
// 判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
} catch (Exception e) {
e.printStackTrace();
return "false";
}
}
}
return "true";
}
@RequestMapping("/download")
public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
String filename = "项目报告.pptx";
String filePath = "E:\\COT";
File file = new File(filePath + "/" + filename);
if (file.exists()) {
// 判断文件父目录是否存在
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// response.setContentType("application/force-download");
response.setHeader("Content-Disposition",
"attachment;fileName=" + java.net.URLEncoder.encode(filename, "UTF-8"));
byte[] buffer = new byte[1024];
FileInputStream fis = null;
// 文件输入流
BufferedInputStream bis = null;
OutputStream os = null;
// 输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("----------file download---" + filename);
try {
bis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
第二种
pom.xml和第一种 一样这这里我就不写了
- application.properties
#默认支持文件上传.
spring.http.multipart.enabled=true
#支持文件写入磁盘.
spring.http.multipart.file-size-threshold=0
# 上传文件的临时目录
#spring.http.multipart.location=
# 最大支持文件大小
spring.http.multipart.max-file-size=10Mb
# 最大支持请求大小
spring.http.multipart.max-request-size=20Mb
- 入口文件
package com.springbootupload2;
import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringBootUpload2Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootUpload2Application.class, args);
}
@Bean
public TomcatServletWebServerFactory tomcatEmbedded() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
// -1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
}
- 工具类
package com.springbootupload2.ulit;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String handleError1(MultipartException e, Model model) {
model.addAttribute("message", e.getCause().getMessage());
return "uploadStatus";
}
}
- controller
package com.springbootupload2.Controller;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
private static final String UPLOADED_FOLDER = "C:\\Users\\赵\\IdeaProjects\\spring-boot-upload2\\src\\main\\resources\\static\\";
@GetMapping("/")
public String file() {
return "file";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file, Model model) {
if (file.isEmpty()) {
model.addAttribute("message", "请选择要上传的文件");
return "/";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
model.addAttribute("message", "上传成功 '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
model.addAttribute("message", "上传异常,请联系管理员!");
}
return "uploadStatus";
}
}
- html
file.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<h1>Spring Boot 文件上传</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
uploadStatus.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<h1>Spring Boot - 上传状态</h1>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>