前言
项目中经常会有上传和下载的需求,这篇文章简述一下springboot项目中实现简单的上传和下载。前台页面使用的thymeleaf模板。
pom.xml文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| <?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/> </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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
<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>
|
创建index.html页面
包含单个上传,下载,批量上传。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <!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>
|
创建IndexController类
用于做页面的跳转
1 2 3 4 5 6 7 8
| @Controller public class IndexController {
@RequestMapping("/") public String index() { return "index"; } }
|
创建FileController类
包含单个上传,单个下载,批量上传对应的方法。
MultipartFile 这个类一般是用来接受前台传过来的文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| @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 "下载失败"; } }
|