-
新建一个SpringBoot项目
-
引入相关的Maven依赖
<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-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
-
修改配置文件application.yml
server: port: 8082 spring: servlet: multipart: max-request-size: 10MB #上传文件总的最大值 max-file-size: 10MB #单个文件的最大值 mvc: view: prefix: templates suffix: .html
-
新建FileController用于文件的上传和下载
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; @Controller @RequestMapping("/api/v1/file") public class FileController { private static final Logger logger = LoggerFactory.getLogger(FileController.class); private static final String filePath = "E:/project/springboot-filedownlowd-upload/src/main/resources/static/file/"; /** * 单个文件上传页面跳转 * @return */ @GetMapping("upload") public String upload(){ logger.info("====upload====="); return "upload"; } /** * 上传单个文件 * @param file * @param redirectAttributes * @return */ @PostMapping("upload") public String upload(@RequestParam(value = "file") MultipartFile file, RedirectAttributes redirectAttributes){ if(file.isEmpty()){ return "文件上传失败,请重新选择文件"; } String fileName = file.getOriginalFilename(); File dest = new File(filePath + fileName); try { file.transferTo(dest); logger.info("文件上传成功"); redirectAttributes.addAttribute("message","文件上传成功"); return "redirect:/api/v1/file/upload"; } catch (IOException e) { e.printStackTrace(); } return "文件上传失败"; } /** * 多个文件上传页面跳转 * @return */ @GetMapping("multiupload") public String multi(){ return "multiupload"; } /** * 多个文件上传 * @param request * @return */ @PostMapping("multiupload") public String multi(HttpServletRequest request){ List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file"); for (int i = 0; i < files.size(); i++) { MultipartFile file = files.get(i); if (file.isEmpty()) { return "上传第" + (i++) + "个文件失败"; } String fileName = file.getOriginalFilename(); File dest = new File(filePath + fileName); try { file.transferTo(dest); logger.info("第" + (i + 1) + "个文件上传成功"); } catch (IOException e) { logger.error(e.toString(), e); } } return "multiupload"; } /** * 文件下载页面跳转 * @return */ @GetMapping("download") public String download(){ return "download"; } /** * 文件下载 * @param fileName * @param request * @param response * @return */ @PostMapping("download") public String download(String fileName, HttpServletRequest request, HttpServletResponse response){ response.setContentType("text/html;charset=utf-8"); try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } BufferedInputStream bis = null; BufferedOutputStream bos = null; String downLoadPath = filePath + File.separator + fileName; //注意不同系统的分隔符 try { long fileLength = new File(downLoadPath).length(); response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(downLoadPath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) try { bis.close(); } catch (IOException e) { e.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } }
-
新增单个文件上传测试页面upload.html
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script type="application/javascript" src=""></script> <title>文件上传</title> </head> <body> <h4>单文件文件上传</h4> <form method="post" action="/api/v1/file/upload" enctype="multipart/form-data"> <input type="file" name="file"><br> <input type="submit" value="提交"> </form> </body> </html>
-
新增多个文件上传的测试页面multiupload.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h4>多文件文件上传</h4> <form method="post" action="/api/v1/file/multiupload" enctype="multipart/form-data"> <input type="file" name="file"><br> <input type="file" name="file"><br> <input type="file" name="file"><br> <input type="submit" value="提交"> </form> </body> </html>
-
新增下载文件测试页面
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form id="download" action="/api/v1/file/download" method="post"> 文件名称: <input type="text" name="fileName" id="fileName"/> <div id="downDiv"> <input id="downloadbtn" type="submit" value="下载文件"> </div> </form> </body> </html>
-
分别访问 http://localhost:8082/api/v1/file/upload http://localhost:8082/api/v1/file/multiupload http://localhost:8082/api/v1/file/download 即可测试上述的单文件上传、多文件上传和文件下载的功能
-
详细代码见 SpringBoot下实现文件上传与下载
SpringBoot2.1.x下实现文件的上传与下载
最新推荐文章于 2024-05-12 06:59:17 发布