前 言
作為一名java程序員,或多或少都會使用到文件的上傳和下載。
比如圖片文件,excel文件等。所以,能快捷的實現對文件的上傳和下載,或者有一個自己的模板,是一件很方便的事情。
今天就帶領大家使用springboot來搭建文件的上傳和下載的模板。其他不多說,直接上代碼!!!
一、創建一個spring boot項目
1.1 開發工具 idea
1.2 jdk 1.8
1.3 具體項目搭建流程可以閱讀我的另一篇博客(創建spring boot項目)
1.4 整體結構
二、搭建spring boot開發環境
2.1 添加pom文件
<?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 https://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.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.liyh</groupId> <artifactId>springboot_file_upload_download</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot_file_upload_download</name> <description>Demo project for Spring Boot</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <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> <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> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.15</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.2 配置application.yml文件
# 配置端口
server:
port: 8085
# 去除thymeleaf的html嚴格校驗
spring:
thymeleaf:
mode: LEGACYHTML5
# 取消模板文件緩存
cache: false
#設定thymeleaf文件路徑 默認為src/main/resources/templates
freemarker:
template-loader-path: classpath:/templates
#設定靜態文件路徑,js,css等
mvc:
static-path-pattern: /static/**
servlet:
multipart:
# 設置單個文件大小
max-file-size: 200MB
# 設置單次請求文件的總大小
max-request-size: 200MB
2.3 編寫摸板文件
<!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 method="POST" enctype="multipart/form-data" action="batch"> <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>
2.4 創建IndexController,FileController
package com.liyh.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @Author: liyh * @Date: 2020/10/12 12:33 */ @Controller public class IndexController { @RequestMapping("/") public String index() { return "index"; } }
package com.liyh.controller; import com.liyh.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; /** * @Author: liyh * @Date: 2020/10/12 11:58 */ @RestController public class FileController { private static final Logger log = LoggerFactory.getLogger(FileController.class); @RequestMapping(value = "/upload") public String upload(@RequestParam("file") MultipartFile file) { try { if (file.isEmpty()) { return "文件為空"; } // 獲取大小 long size = file.getSize(); log.info("文件大小: " + size); // 判斷上傳文件大小 if (!FileUtils.checkFileSize(file,50,"M")) { log.error("上傳文件規定小於50MB"); return "上傳文件規定小於50MB"; } // 獲取文件名 String fileName = file.getOriginalFilename(); log.info("上傳的文件名為:" + fileName); // 獲取文件的后綴名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); log.info("文件的后綴名為:" + suffixName); // 設置文件存儲路徑 String filePath = "C:/software/file/"; String path = filePath + fileName; File dest = new File(path); // 檢測是否存在目錄 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs();// 新建文件夾 } file.transferTo(dest);// 文件寫入 return "上傳成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException 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 = "C:/software/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 = "timg.jpg";// 文件名 String result = FileUtils.downloadFiles(request, response, fileName); if (request == null) { return null; } return result; } }
2.4 判斷文件大小的工具類FileUtils

package com.liyh.utils; import org.springframework.core.io.ClassPathResource; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; /** * @Author: liyh * @Date: 2020/11/4 16:10 */ public class FileUtils { /** * 下載文件 * @param request * @param response * @param fileName * @return * @throws IOException */ public static String downloadFiles(HttpServletRequest request, HttpServletResponse response, String fileName){ if (StringUtils.isEmpty(fileName)) { return "文件名稱為空"; } //設置文件路徑 ClassPathResource classPathResource = new ClassPathResource("templates/" + fileName); File file = null; try { file = classPathResource.getFile(); } catch (IOException e) { e.printStackTrace(); return "文件不存在"; } response.setHeader("content-type", "application/octet-stream"); // 設置強制下載不打開 response.setContentType("application/force-download"); // 設置文件名 response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); byte[] buffer = new byte[1024]; InputStream 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); } } 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 "文件下載成功"; } /** * 判斷文件大小 * * @param file 文件 * @param size 限制大小 * @param unit 限制單位(B,K,M,G) * @return */ public static boolean checkFileSize(MultipartFile file, int size, String unit) { if (file.isEmpty() || StringUtils.isEmpty(size) || StringUtils.isEmpty(unit)) { return false; } long len = file.getSize(); double fileSize = 0; if ("B".equals(unit.toUpperCase())) { fileSize = (double) len; } else if ("K".equals(unit.toUpperCase())) { fileSize = (double) len / 1024; } else if ("M".equals(unit.toUpperCase())) { fileSize = (double) len / 1048576; } else if ("G".equals(unit.toUpperCase())) { fileSize = (double) len / 1073741824; } if (fileSize > size) { return false; } return true; } }
三、摸板文件
四、啟動項目,進行測試
4.1 啟動項目,訪問結果:
4.2 測試單個文件上傳
4.2.1 測試小於50MB的文件
測試結果(文件上傳成功):
4.2.2 測試大於50MB的文件
測試結果(文件上傳失敗):
注意:在上傳文件時,tomcat默認上傳文件大小為1mb,當上傳文件太大時會報錯,要在application.yml配置上傳文件大小,然后才FileController去判斷文件大小,大於50MB上傳失敗!!!
4.3 測試文件下載
4.4 測試多個文件
測試結果(文件上傳成功):
4.4 項目地址:項目