SpringBoot 文件上传下载
2019-08-19 本文已影响0人
月弦
前言
项目中经常会有上传和下载的需求,这篇文章简述一下springboot项目中实现简单的上传和下载。前台页面使用的thymeleaf模板。
1、pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.huzh</groupId>
<artifactId>springboot-upload-download</artifactId>
<version>1.0-SNAPSHOT</version>
<name>springboot-upload-download</name>
<description>springboot-upload-download</description>
<properties>
<java.version>1.8</java.version>
<nekohtml.version>1.9.22</nekohtml.version>
</properties>
<dependencies>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--HTML解析器和标记平衡器。-->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>${nekohtml.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、创建index.html页面
包含单个上传,下载,批量上传。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>单文件上传</p>
<form action="upload" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="file"/>
<input type="submit"/>
</form>
<hr/>
<p>文件下载</p>
<a href="download">下载文件</a>
<hr/>
<p>多文件上传</p>
<form action="batch" method="POST" enctype="multipart/form-data">
<p>文件1:<input type="file" name="file"/></p>
<p>文件2:<input type="file" name="file"/></p>
<p><input type="submit" value="上传"/></p>
</form>
</body>
</html>
3、创建IndexController类
用于做页面的跳转
@Controller
public class IndexController {
@RequestMapping("/")
public String index() {
return "index";
}
}
4、创建FileController类
包含单个上传,单个下载,批量上传对应的方法。
MultipartFile 这个类一般是用来接受前台传过来的文件。
@RestController
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@RequestMapping(value = "upload")
public String upload(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
logger.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("文件的后缀名为:" + suffixName);
//设置文件存储路径
String filePath = "D:/huzh/workspace/springboot_workspace/file/";
String path = filePath + fileName;
File dest = new File(path);
if (!dest.getParentFile().exists()) {
//新建文件
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return "上传成功";
} catch (Exception e) {
e.printStackTrace();
}
return "上传失败";
}
@PostMapping("/batch")
public String handleFileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size(); i++) {
file = files.get(i);
String filePath = "D:/huzh/workspace/springboot_workspace/file/";
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(
//设置文件路径及名字
new File(filePath + file.getOriginalFilename())));
stream.write(bytes);
stream.close();
} catch (Exception e) {
stream = null;
return "第 " + i + " 个文件上传失败 ==> "
+ e.getMessage();
}
} else {
return "第 " + i
+ " 个文件上传失败因为文件为空";
}
}
return "上传成功";
}
@GetMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "123.jpg";
if (fileName != null) {
File file = new File("D:/huzh/workspace/springboot_workspace/file/1.jpg");
if (file.exists()) {
// 设置强制下载不打开
response.setContentType("application/force-download");
// 设置文件名
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
return "下载成功";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "下载失败";
}
}