[JAVA] SpringBoot文件上传与下载功能实现详解

1660 0
黑夜隐士 2022-11-8 17:58:07 | 显示全部楼层 |阅读模式
目录

    前言1、引入Apache Commons FileUpload组件依赖2、设置上传文件大小限制3、创建选择文件视图页面4、创建控制器5、创建文件下载视图页面


前言

文件上传与下载是Web应用开发中常用的功能之一,在实际的Web应用开发中,为了成功上传文件,必须将表单的method设置为post,并将enctype设置为multipart/form-data 只有这样设置,浏览器才能将所选文件的二进制数据发送给服务器
从Servlet3.0开始,就提供了处理文件上传的方法,但这种文件上传需要在Java Servlet中完成,而Spring MVC提供了更简单的封装。Spring MVC是通过Apache Commons FileUpload技术实现一个MultipartResolver的实现类CommonsMultipartResovler完成文件上传的。因此,Spring MVC的文件上传需要依赖Apache Commons FileUpload组件
Spring MVC将上传文件自动绑定到MultipartFile对象中,MultipartFile提供了获取上传文件内容,文件名等方法。并通过transferTo方法将文件上传到服务器的磁盘中,MultipartFile常用方法如下
byte[]getBytes() 获取文件数据
String getContentType() 获取文件MIME类型
InputStream getInputStream() 获取表单中文件组件的名字
String getName() 获取表单中文件组件的名字
String getOriginalFilename() 获取上传文件的原名
long getSize() 获取文件的字节大小
boolean isEmpty() 是否有选择上传文件
void transferTo() 将上传文件保存到一个目标文件中
Sprng Boot的spring-boot-starter-web已经集成了Spring MVC 所以使用Spring Boot实现文件上传更加敏捷,只需引入Apache Commons FileUpload组件依赖即可
下面通过一个实例来加深理解
操作步骤如下

1、引入Apache Commons FileUpload组件依赖

在Web应用的ch5_2的pom.xml文件中 添加Apache Commons FileUpload组件依赖 代码如下
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. -<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">
  3. <modelVersion>4.0.0</modelVersion>
  4. -<parent>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter-parent</artifactId>
  7. <version>2.1.5.RELEASE</version>
  8. <relativePath/>
  9. <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.ch</groupId>
  12. <artifactId>ch5_2</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>ch5_2</name>
  15. <description>Demo project for Spring Boot</description>
  16. -<properties>
  17. <java.version>11</java.version>
  18. </properties>
  19. -<dependencies>
  20. -<dependency>
  21. <groupId>commons-fileupload</groupId>
  22. <artifactId>commons-fileupload</artifactId>
  23. <!-- 由于commons-fileupload组件不属于Spring Boot,所以需要加上版本 -->
  24. <version>1.3.3</version>
  25. </dependency>
  26. -<dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  29. </dependency>
  30. -<dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-web</artifactId>
  33. </dependency>
  34. -<dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-test</artifactId>
  37. <scope>test</scope>
  38. </dependency>
  39. </dependencies>
  40. -<build>
  41. -<plugins>
  42. -<plugin>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-maven-plugin</artifactId>
  45. </plugin>
  46. </plugins>
  47. </build>
  48. </project>
复制代码
2、设置上传文件大小限制

在Web应用的ch5_2的配置文件application。properties中 添加如下配置限制上传文件大小
server.servlet.context-path=/ch5_2
#上传文件时,默认单个上传文件大小是1MB,max-file-size设置单个上传文件大小
spring.servlet.multipart.max-file-size=50MB
#默认总文件大小是10MB,max-request-size设置总上传文件大小
spring.servlet.multipart.max-request-size=500MB

3、创建选择文件视图页面

在ch5_2应用的src/main/resources/templates目录下 创建选择文件视图页面uploadFile.html 该页面中有一个enctype属性值为multipart/form-data的form表单 部分代码如下
  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. <link rel="stylesheet" th:href="@{css/bootstrap.min.css}" rel="external nofollow"  />
  7. <!-- 默认访问 src/main/resources/static下的css文件夹-->
  8. <link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" rel="external nofollow"  />
  9. </head>
  10. <body>
  11. <div class="panel panel-primary">
  12.                 <div class="panel-heading">
  13.                         <h3 class="panel-title">文件上传示例</h3>
  14.                 </div>
  15.         </div>
  16.         <div class="container">
  17.                 <div class="row">
  18.                         <div class="col-md-6 col-sm-6">
  19.                                 <form class="form-horizontal" action="upload" method="post" enctype="multipart/form-data">
  20.                                         <div class="form-group">
  21.                                                 <div class="input-group col-md-6">
  22.                                                         <span class="input-group-addon">
  23.                                                                 <i class="glyphicon glyphicon-pencil"></i>
  24.                                                         </span>
  25.                                                         <input class="form-control" type="text"
  26.                                                          name="description" th:placeholder="文件描述"/>
  27.                                 </form>
  28.                         </div>
  29.                 </div>
  30.         </div>
  31. </body>
  32. </html>
复制代码
4、创建控制器

在ch5_2应用的com.ch.ch5_2.controller包中 创建控制器类TestFileUpload 在该类中有4个处理方法一个是界面导航方法,uploadfile 一个是实现文件上传的upload方法,一个是显示将要被下载文件的showDownLoad 方法,一个是实现下载功能的download方法 部分代码如下
  1. package com.ch.ch5_2.controller;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.net.URLEncoder;
  5. import javax.servlet.http.HttpServletRequest;
  6. import org.apache.commons.io.FileUtils;
  7. import org.springframework.http.MediaType;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.http.ResponseEntity.BodyBuilder;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.ui.Model;
  12. import org.springframework.web.bind.annotation.RequestHeader;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RequestParam;
  15. import org.springframework.web.multipart.MultipartFile;
  16. @Controller
  17. public class TestFileUpload {
  18.         /**
  19.          * 进入文件选择页面
  20.          */
  21.         @RequestMapping("/uploadFile")
  22.         public String uploadFile() {
  23.                 return "uploadFile";
  24.         }
  25.         /**
  26.          * 上传文件自动绑定到MultipartFile对象中,
  27.          * 在这里使用处理方法的形参接收请求参数。
  28.          * @throws IOException
  29.          * @throws IllegalStateException
  30.          */
  31.         @RequestMapping("/upload")
  32.         public String upload(
  33.                         HttpServletRequest request,
  34.                         @RequestParam("description") String description,
  35.                         @RequestParam("myfile") MultipartFile myfile) throws IllegalStateException, IOException {
  36.                 System.out.println("文件描述:" + description);
  37.                 //如果选择了上传文件,将文件上传到指定的目录uploadFiles
  38.                 if(!myfile.isEmpty()) {
  39.                         //上传文件路径
  40.                         String path = request.getServletContext().getRealPath("/uploadFiles/");
  41.                         //获得上传文件原名
  42.                         String fileName = myfile.getOriginalFilename();
  43.         }
  44.         /**
  45.          * 实现下载功能
  46.          * @throws IOException
  47.          */
  48.         @RequestMapping("/download")
  49.         public ResponseEntity<byte[]> download(
  50.                         HttpServletRequest request,
  51.                         @RequestParam("filename") String filename,
  52.                         @RequestHeader("User-Agent") String userAgent) throws IOException {
  53.                 //下载文件路径
  54.                 String path = request.getServletContext().getRealPath("/uploadFiles/");
  55.                 //构建将要下载的文件对象
  56.                 File downFile = new File(path + File.separator + filename);
  57.                 //ok表示HTTP中的状态是200
  58.                 BodyBuilder builder =  ResponseEntity.ok();
  59.                 //内容长度
  60.                 builder.contentLength(downFile.length());
  61.                 //application/octet-stream:二进制流数据(最常见的文件下载)
  62.                 builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
  63.                 //使用URLEncoder.encode对文件名进行编码
  64.                 filename = URLEncoder.encode(filename,"UTF-8");
  65.                 /**
  66.                  * 设置实际的响应文件名,告诉浏览器文件要用于“下载”和“保存”。
  67.                  * 不同的浏览器,处理方式不同,根据浏览器的实际情况区别对待。
  68.                  */
  69.                 if(userAgent.indexOf("MSIE") > 0) {
  70.                         //IE浏览器,只需要用UTF-8字符集进行URL编码
  71.                         builder.header("Content-Disposition", "attachment; filename=" + filename);
  72.                 }else {
  73.                         /**非IE浏览器,如FireFox、Chrome等浏览器,则需要说明编码的字符集
  74.                          * filename后面有个*号,在UTF-8后面有两个单引号
  75.                          */
  76.                         builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
  77.                 }
  78.                 return builder.body(FileUtils.readFileToByteArray(downFile));
  79.         }
  80. }
复制代码
5、创建文件下载视图页面

创建视图页面showFile.html
  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert t
  6.                                 </div>
  7.                         </div>
  8.                 </div>
  9.         </div>
  10. </body>
  11. </html>
复制代码


同样运行Ch52Application主类 然后访问http://localhost:8080/ch5_2/uploadFile
效果如下


点击选择文件后弹出如下弹窗


假如没有上传文件 点击上传文件以后如下


到此这篇关于SpringBoot文件上传与下载功能实现详解的文章就介绍到这了,更多相关SpringBoot文件上传与下载内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

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

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行