SpringMVC实现文件上传&下载功能

十念  金牌会员 | 2024-4-17 08:36:57 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 893|帖子 893|积分 2679

文件上传

说明:
使用maven构建web工程。
使用Thymeleaf技术进行服务器页面渲染。
使用ResponseEntity实现下载文件的功能。
  1. @Controller
  2. public class FileDownloadAndUpload {
  3.     @GetMapping("/file/download")
  4.     public ResponseEntity<byte[]> fileDownload(HttpSession session) {
  5.         //获取servletContext对象
  6.         ServletContext servletContext = session.getServletContext();
  7.         /*
  8.         路径空串:maven工程中获取的是当前web工程target下的war包路径
  9.         D:\spring-workspace\springmvc-pro\springmvc-filedownupload\target\springmvc-filedownupload-1.0-SNAPSHOT
  10.          */
  11.         //String realPath = servletContext.getRealPath("");
  12.         //获取服务器中文件的真实路径
  13.         String path = File.separator + "imgs" + File.separator + "dog.jpg";
  14.         String realPath = servletContext.getRealPath(path);
  15.         ResponseEntity<byte[]> responseEntity = null;
  16.         try (
  17.                 //创建字节输入流
  18.                 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath))
  19.         ) {
  20.             //创建字节数组
  21.             byte[] buff = new byte[bis.available()];
  22.             //将流读入到字节数组中
  23.             bis.read(buff);
  24.             //创建HttpHeaders对象设置响应头信息
  25.             MultiValueMap<String, String> headers = new HttpHeaders();
  26.             //设置要下载方式以及下载文件的名字
  27.             headers.add("Content-Disposition", "attachment;filename=dog.jpg");
  28.             //设置响应状态码
  29.             HttpStatus statusCode = HttpStatus.OK;
  30.             //创建ResponseEntity对象
  31.             responseEntity = new ResponseEntity<>(buff, headers, statusCode);
  32.             return responseEntity;
  33.         }  catch (IOException e) {
  34.             e.printStackTrace();
  35.         }
  36.         throw new RuntimeException("文件下载出现异常");
  37.     }
  38. }
复制代码
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>文件上传</title>
  6. </head>
  7. <body>
  8.     <a th:target="_blank" href="https://www.cnblogs.com/@{/file/download}">文件下载</a><br/>
  9. </body>
  10. </html>
复制代码
文件下载

文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data"。
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息。
实现文件下载步骤:
step 1: 添加依赖
  1. <dependency>
  2.         <groupId>commons-fileupload</groupId>
  3.         <artifactId>commons-fileupload</artifactId>
  4.         <version>1.3.3</version>
  5. </dependency>
复制代码
step 2:在springmvc配置文件中添加文件解析器
  1. [/code]setp 3:编写文件下载逻辑
  2. [code]@Controller
  3. public class FileDownloadAndUpload {
  4. @PostMapping("/file/upload")
  5.     public String fileUpload(@RequestParam("photo") MultipartFile photo, HttpSession session) {
  6.         //获取servletContext对象
  7.         ServletContext servletContext = session.getServletContext();
  8.         //获取上传文件的文件名
  9.         String filename = photo.getOriginalFilename();
  10.         //文件重命名问题
  11.         if (filename != null) {
  12.             //获取文件后缀
  13.             String suffixFileName = filename.substring(filename.lastIndexOf("."));
  14.             //通过UUID重命名文件名
  15.             filename = UUID.randomUUID().toString() + suffixFileName;
  16.         }
  17.         //获取服务器中文件所在路径
  18.         String realPath = servletContext.getRealPath("imgs");
  19.         File file = new File(realPath);
  20.         //判断文件目录是否存在
  21.         if (!file.exists()) {
  22.             file.mkdir();
  23.         }
  24.         //文件最终上传的路径
  25.         String filePath = realPath + File.separator + filename;
  26.         //实现上传
  27.         try {
  28.             photo.transferTo(new File(filePath));
  29.         } catch (IOException e) {
  30.             e.printStackTrace();
  31.         }
  32.         return "success";
  33.     }
  34. }
复制代码
step 4:编写form表单
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>文件下载</title>
  6. </head>
  7. <body>
  8.     <form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
  9.         <input type="file" name="photo"><br/>
  10.         <input type="submit" value="点击上传"><br/>
  11.     </form>
  12. </body>
  13. </html>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

十念

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表