SpringBoot.08.SpringBoot文件上传与下载

x33g5p2x  于2022-04-11 转载在 Spring  
字(18.2k)|赞(0)|评价(0)|浏览(1127)

前言

文件操作包括文件上传文件下载

用户将自己计算机中文件上传到项目所在服务器|文件服务器|OSS的过程 称之为文件上传;文件下载则相反。下面我们先来看下文件上传

文件上传

由于本次案例会涉及到页面(jsp)操作,所以不要忘记添加配置jsp相关的东西

1.新建Module

新建Module - springboot-07-file,按照下图所示填写信息:

点击下一步选择依赖Spring Web,点击Finish。如下图所示:

2.项目配置

我们在springboot-06-AOP中的代码上进行改造。首先我们规整一下项目,然后将springboot-06-AOP中的代码拷贝过来,去除AOP相关的代码。如下图所示:

3.pom.xml

pom.xml文件中新增了jsp有关的依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.5.0</version>
  9. <relativePath/>
  10. </parent>
  11. <groupId>com.christy</groupId>
  12. <artifactId>springboot-07-file</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springboot-07-file</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <!-- spring-boot-starter-web -->
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <!-- spring-boot-starter-test -->
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-test</artifactId>
  29. <scope>test</scope>
  30. </dependency>
  31. <!-- druid -->
  32. <dependency>
  33. <groupId>com.alibaba</groupId>
  34. <artifactId>druid</artifactId>
  35. <version>1.2.6</version>
  36. </dependency>
  37. <!-- mysql-connector-java -->
  38. <dependency>
  39. <groupId>mysql</groupId>
  40. <artifactId>mysql-connector-java</artifactId>
  41. <version>5.1.38</version>
  42. </dependency>
  43. <!-- mybatis-spring-boot-starter
  44. 由于springboot整合mybatis版本中默认依赖mybatis 因此不需要额外引入mybati版本,否则会出现冲突
  45. -->
  46. <dependency>
  47. <groupId>org.mybatis.spring.boot</groupId>
  48. <artifactId>mybatis-spring-boot-starter</artifactId>
  49. <version>2.1.4</version>
  50. </dependency>
  51. <!-- 每次新建的项目如果需要开启热部署都需要引入该依赖 -->
  52. <dependency>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-devtools</artifactId>
  55. <optional>true</optional>
  56. </dependency>
  57. <!-- lombok -->
  58. <dependency>
  59. <groupId>org.projectlombok</groupId>
  60. <artifactId>lombok</artifactId>
  61. </dependency>
  62. <!-- c标签库 -->
  63. <dependency>
  64. <groupId>jstl</groupId>
  65. <artifactId>jstl</artifactId>
  66. <version>1.2</version>
  67. </dependency>
  68. <!-- 让内嵌tomcat具有解析jsp功能 -->
  69. <dependency>
  70. <groupId>org.apache.tomcat.embed</groupId>
  71. <artifactId>tomcat-embed-jasper</artifactId>
  72. </dependency>
  73. <!-- 文件上传相关 -->
  74. <dependency>
  75. <groupId>commons-io</groupId>
  76. <artifactId>commons-io</artifactId>
  77. <version>2.8.0</version>
  78. </dependency>
  79. <dependency>
  80. <groupId>commons-fileupload</groupId>
  81. <artifactId>commons-fileupload</artifactId>
  82. <version>1.4</version>
  83. <exclusions>
  84. <exclusion>
  85. <groupId>commons-io</groupId>
  86. <artifactId>commons-io</artifactId>
  87. </exclusion>
  88. </exclusions>
  89. </dependency>
  90. </dependencies>
  91. <build>
  92. <plugins>
  93. <!-- 一定要注意mvn的插件一定是1.4.2.RELEASE,否则jsp访问不到 -->
  94. <plugin>
  95. <groupId>org.springframework.boot</groupId>
  96. <artifactId>spring-boot-maven-plugin</artifactId>
  97. <version>1.4.2.RELEASE</version>
  98. </plugin>
  99. </plugins>
  100. <resources>
  101. <!-- 打包时将jsp文件拷贝到META-INF目录下-->
  102. <resource>
  103. <!-- 指定resources插件处理哪个目录下的资源文件 -->
  104. <directory>src/main/webapp</directory>
  105. <!-- 注意必须要放在此目录下才能被访问到 -->
  106. <targetPath>META-INF/resources</targetPath>
  107. <includes>
  108. <include>**/**</include>
  109. </includes>
  110. </resource>
  111. <resource>
  112. <directory>src/main/resources</directory>
  113. <includes>
  114. <include>**/**</include>
  115. </includes>
  116. <filtering>false</filtering>
  117. </resource>
  118. </resources>
  119. </build>
  120. </project>

4.application-dev.yml

  1. server:
  2. port: 8807
  3. # 修改jsp无须重启应用
  4. servlet:
  5. jsp:
  6. init-parameters:
  7. development: true
  8. # datasource
  9. spring:
  10. datasource:
  11. type: com.alibaba.druid.pool.DruidDataSource
  12. driver-class-name: com.mysql.jdbc.Driver
  13. url: jdbc:mysql://localhost:3306/christy?characterEncoding=UTF-8
  14. username: root
  15. password: 123456
  16. # 配置视图解析器
  17. mvc:
  18. view:
  19. prefix: / #这个代表jsp的根路径 需要在java包下新建webapp目录
  20. suffix: .jsp
  21. # 配置文件上传大小
  22. servlet:
  23. multipart:
  24. max-request-size: 10MB # 设置请求的数据最大为10MB
  25. max-file-size: 10MB # 设置能够处理的单个文件最大值为10MB
  26. # mybatis
  27. mybatis:
  28. mapper-locations: classpath:com/christy/mapper/*.xml
  29. type-aliases-package: com.christy.entity
  30. # logback
  31. # logging:
  32. # level:
  33. # root: info # 指定全局根日志级别为INFO(默认)
  34. # com.christy.mapper: debug # 指定包级别日志为debug,在控制台不打印DEBUG日志时能看到sql语句
  35. # 多环境下我们需要指定当前使用的日志文件
  36. logging:
  37. config: classpath:logs/logback-spring-dev.xml
  38. # 文件上传路径
  39. file:
  40. # window下文件上传路径
  41. windows:
  42. path: G:/files/
  43. # linux下文件上传路径
  44. linux:
  45. path: /usr/files/
  46. # 虚拟路径
  47. virtual:
  48. path: /files/

有关配置相关说明

1.设置文件上传大小

  1. # 配置文件上传大小
  2. servlet:
  3. multipart:
  4. max-request-size: 10MB # 设置请求的数据最大为10MB
  5. max-file-size: 10MB # 设置能够处理的单个文件最大值为10MB

SpringBoot默认上传大小是1048576 bytes,也就是1MB(也有说是10MB的,但是我的是1MB),这里改为10MB,否则会报如下错误:

2.设置文件上传路径及虚拟路径

  1. # 文件上传路径
  2. file:
  3. # window下文件上传路径
  4. windows:
  5. path: G:/files/
  6. # linux下文件上传路径
  7. linux:
  8. path: /usr/files/
  9. # 虚拟路径
  10. virtual:
  11. path: /files/

5.设置Working directory

我们选择Edit Configuration,在Working directory中选择MODULE_DIR,然后点击Apply->OK。如下图所示:

6.upload.jsp

  1. <%@ page pageEncoding="UTF-8" language="java" contentType="text/html; UTF-8" %>
  2. <!doctype html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>springboot文件上传</title>
  9. </head>
  10. <body>
  11. <h1>文件上传</h1>
  12. <%--
  13. methodpost 含有文件上传的页面提交方式必须是POST
  14. enctype:该属性规定在发送到服务器之前应该如何对表单数据进行编码
  15. 默认地,表单数据会编码为 "application/x-www-form-urlencoded"。就是说,在发送到服务器之前,
  16. 所有字符都会进行编码(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。但是该种方式不能编码文件
  17. 在有文件的情况下,该值要修改为:multipart/form-data
  18. --%>
  19. <form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data">
  20. <input type="file" name="file">
  21. <input type="submit" value="上传">
  22. </form>
  23. </body>
  24. </html>

7.File相关

7.1 FileController.java
  1. import com.christy.utils.FileUtils;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. import javax.servlet.http.HttpServletRequest;
  7. import java.io.IOException;
  8. /**
  9. * @Author Christy
  10. * @Date 2021/9/14 16:28
  11. **/
  12. @Controller
  13. @RequestMapping("/file")
  14. public class FileController {
  15. private FileUtils fileUtils;
  16. @Autowired
  17. public FileController(FileUtils fileUtils) {
  18. this.fileUtils = fileUtils;
  19. }
  20. /**
  21. * MultipartFile file: 文件接收对象 file变量名要与form表单中input type="file"标签中的name属性一致
  22. *
  23. * @author Christy
  24. * @date 2021/9/15 13:57
  25. * @param request
  26. * @return java.lang.String
  27. */
  28. @RequestMapping("/upload")
  29. @ResponseBody
  30. public String upload(HttpServletRequest request) {
  31. try {
  32. fileUtils.fileUpload(request);
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. return "文件上传失败";
  36. }
  37. return "文件上传成功";
  38. }
  39. }
7.2 FileConstants.java
  1. import org.springframework.beans.factory.annotation.Value;
  2. import org.springframework.stereotype.Component;
  3. /**
  4. * @Author Christy
  5. * @Date 2021/9/15 16:35
  6. **/
  7. @Component
  8. public class FileConstants {
  9. /**
  10. * windows文件上传储存的地址
  11. */
  12. public static String fileWindowsPath;
  13. /**
  14. * linux文件上传储存的地址
  15. */
  16. public static String fileLinuxPath;
  17. /**
  18. * 文件上传虚拟路径
  19. */
  20. public static String fileVirtualPath;
  21. @Value("${file.windows.path}")
  22. public void setFileWindowsPath(String w) {
  23. fileWindowsPath = w;
  24. }
  25. @Value("${file.linux.path}")
  26. public void setFileLinuxPath(String l) {
  27. fileLinuxPath = l;
  28. }
  29. @Value("${file.virtual.path}")
  30. public void setFileVirtualPath(String v) {
  31. fileVirtualPath = v;
  32. }
  33. }
7.3 FileUtils.java
  1. import com.christy.constants.FileConstants;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.web.multipart.MultipartFile;
  5. import org.springframework.web.multipart.MultipartHttpServletRequest;
  6. import org.springframework.web.multipart.commons.CommonsMultipartResolver;
  7. import javax.servlet.http.HttpServletRequest;
  8. import java.io.File;
  9. import java.io.IOException;
  10. import java.util.Iterator;
  11. import java.util.UUID;
  12. /**
  13. * @Author Christy
  14. * @Date 2021/9/15 14:29
  15. **/
  16. @Component
  17. @Slf4j
  18. public class FileUtils {
  19. public String getRealPath(){
  20. String filePath = "";
  21. String os = System.getProperty("os.name");
  22. if(os.toLowerCase().startsWith("win")){
  23. filePath = FileConstants.fileWindowsPath;
  24. } else {
  25. filePath = FileConstants.fileLinuxPath;
  26. }
  27. File file = new File(filePath);
  28. if(!file.exists() || !file.isDirectory()){
  29. file.mkdirs();
  30. }
  31. return filePath;
  32. }
  33. public void fileUpload(HttpServletRequest request) throws IOException {
  34. CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
  35. if (multipartResolver.isMultipart(request)) {
  36. MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
  37. Iterator<String> iterator = multiRequest.getFileNames();
  38. while (iterator.hasNext()) {
  39. // 上传的文件
  40. MultipartFile item = multiRequest.getFile(iterator.next());
  41. if (item != null) {
  42. log.info("文件名:" + item.getOriginalFilename());
  43. log.info("文件类型:" + item.getContentType());
  44. log.info("文件大小:" + item.getSize());
  45. // 文件的原始名称
  46. String originalFilename = item.getOriginalFilename();
  47. String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
  48. // 如果名称不为“”,说明该文件存在,否则说明该文件不存在
  49. if (!"".equals(originalFilename.trim())) {
  50. String newFileName = UUID.randomUUID() + ext;
  51. String filePath = getRealPath();
  52. //不是图片,直接保存
  53. item.transferTo(new File(filePath, newFileName));
  54. }
  55. }
  56. }
  57. }
  58. }
  59. }

8.MyWebMvcConfigurer.java

  1. import com.christy.constants.FileConstants;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  4. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  5. /**
  6. * @Author Christy
  7. * @Date 2021/9/15 16:24
  8. **/
  9. @Configuration
  10. public class MyWebMvcConfigurer implements WebMvcConfigurer {
  11. @Override
  12. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  13. /**
  14. * 文件上传到服务器后并不能在项目中直接访问,需要将磁盘路径映射成虚拟路径使用http://domain/的方式才可以
  15. */
  16. String os = System.getProperty("os.name");
  17. if(os.toLowerCase().startsWith("win")){
  18. // Windows虚拟路径映射本地磁盘
  19. registry.addResourceHandler(FileConstants.fileVirtualPath + "**").addResourceLocations("file:" + FileConstants.fileWindowsPath);
  20. } else {
  21. // Linux虚拟路径映射本地磁盘
  22. registry.addResourceHandler(FileConstants.fileVirtualPath + "**").addResourceLocations("file:" + FileConstants.fileLinuxPath);
  23. }
  24. }
  25. }

9.测试

9.1 windows下

我们启动项目,浏览器打开upload.jsp页面,我们选择一张图片。如下所示:

点击上传按钮,注意观察控制台和页面。成功的情况如下所示:

我们在浏览器中访问http://localhost:8807/files/e8fdb612-1fe8-4e4c-a3df-04297eef0267.jpg,图片能够正常加载。如下图所示:

9.2 linux下

我们启动虚拟机Christy(BaseOS),IP地址为192.168.8.100。进入到/usr/apps/目录下,上传jar包至该目录。如下图所示:

执行java -jar springboot-07-file-0.0.1-SNAPSHOT.jar命令,启动该项目。如下图所示:

我们在浏览器中访问http://192.168.8.100:8807/upload.jsp,还是选择上面的图片。如下图所示:

点击上传,页面返回文件上传成功,控制台也能够打印输出文件信息。如下图所示:

我们回到目录/usr/files,可以找到刚才上传的图片。如下图所示:

我们 浏览器访问http://192.168.8.100:8807/files/29b3b42c-f72f-462a-b6f9-d19afcfeab1c.jpg,图片也可以正常加载。如下图所示:

文件下载

相比较于文件上传,文件下载就简单多了。首先我们要提供文件的下载地址,就拿上面我们上传的照片来说,他的访问地址就是我们的下载地址

在Windows中的下载地址:

http://localhost:8807/files/e8fdb612-1fe8-4e4c-a3df-04297eef0267.jpg

在Linux中的下载地址:

http://192.168.8.100:8807/files/29b3b42c-f72f-462a-b6f9-d19afcfeab1c.jpg

1.download.jsp

  1. <%@ page pageEncoding="UTF-8" language="java" contentType="text/html; UTF-8" %>
  2. <!doctype html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>springboot文件下载</title>
  9. </head>
  10. <body>
  11. <h1>文件下载</h1>
  12. <%--
  13. a标签里面的filePath就是我们最终保存到数据库中的文件路径,这里不要搞错了
  14. --%>
  15. <a
  16. href="${pageContext.request.contextPath}/file/download?fileName=e8fdb612-1fe8-4e4c-a3df-04297eef0267.jpg&filePath=/files/e8fdb612-1fe8-4e4c-a3df-04297eef0267.jpg">
  17. 睡美人-windows
  18. </a>
  19. <br/>
  20. <a
  21. href="${pageContext.request.contextPath}/file/download?fileName=29b3b42c-f72f-462a-b6f9-d19afcfeab1c.jpg&filePath=/files/29b3b42c-f72f-462a-b6f9-d19afcfeab1c.jpg">
  22. 睡美人-linux</a>
  23. </body>
  24. </html>

2.FIleController.java

  1. import com.christy.utils.FileUtils;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import java.io.IOException;
  8. /**
  9. * @Author Christy
  10. * @Date 2021/9/14 16:28
  11. **/
  12. @RestController
  13. @RequestMapping("/file")
  14. public class FileController {
  15. private FileUtils fileUtils;
  16. @Autowired
  17. public FileController(FileUtils fileUtils) {
  18. this.fileUtils = fileUtils;
  19. }
  20. /**
  21. * MultipartFile file: 文件接收对象 file变量名要与form表单中input type="file"标签中的name属性一致
  22. *
  23. * @author Christy
  24. * @date 2021/9/15 13:57
  25. * @param request
  26. * @return java.lang.String
  27. */
  28. @RequestMapping("/upload")
  29. public String upload(HttpServletRequest request) {
  30. try {
  31. fileUtils.fileUpload(request);
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. return "文件上传失败";
  35. }
  36. return "文件上传成功";
  37. }
  38. @RequestMapping("/download")
  39. public String download(HttpServletResponse response, String fileName, String filePath){
  40. try {
  41. return fileUtils.fileDownload(response, fileName, filePath);
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. return "文件下载失败!";
  45. }
  46. }
  47. }

3.FileUtils.java

  1. import com.christy.constants.FileConstants;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.util.FileCopyUtils;
  5. import org.springframework.web.multipart.MultipartFile;
  6. import org.springframework.web.multipart.MultipartHttpServletRequest;
  7. import org.springframework.web.multipart.commons.CommonsMultipartResolver;
  8. import javax.servlet.ServletOutputStream;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.File;
  12. import java.io.FileInputStream;
  13. import java.io.IOException;
  14. import java.net.URLEncoder;
  15. import java.util.Iterator;
  16. import java.util.UUID;
  17. /**
  18. * @Author Christy
  19. * @Date 2021/9/15 14:29
  20. **/
  21. @Component
  22. @Slf4j
  23. public class FileUtils {
  24. /**
  25. * 获取文件上传的真实路径
  26. * @author Christy
  27. * @date 2021/9/17 10:02
  28. * @param
  29. * @return java.lang.String
  30. */
  31. public String getUploadRealPath(){
  32. String filePath = "";
  33. String os = System.getProperty("os.name");
  34. if(os.toLowerCase().startsWith("win")){
  35. filePath = FileConstants.fileWindowsPath;
  36. } else {
  37. filePath = FileConstants.fileLinuxPath;
  38. }
  39. File file = new File(filePath);
  40. if(!file.exists() || !file.isDirectory()){
  41. file.mkdirs();
  42. }
  43. return filePath;
  44. }
  45. /**
  46. * 获取文件下载的真实路径
  47. * @author Christy
  48. * @date 2021/9/17 10:02
  49. * @param
  50. * @return java.lang.String
  51. */
  52. public String getDownloadRealPath(String filePath){
  53. String realPath = "";
  54. if(filePath.indexOf(FileConstants.fileVirtualPath) == 0){
  55. String os = System.getProperty("os.name");
  56. // 将文件的虚拟路径替换成物理路径
  57. if(os.toLowerCase().startsWith("win")){
  58. StringBuilder stringbuilder = new StringBuilder(filePath);
  59. stringbuilder.replace(0, FileConstants.fileVirtualPath.length(), FileConstants.fileWindowsPath);
  60. realPath = stringbuilder.toString();
  61. } else {
  62. StringBuilder stringbuilder = new StringBuilder(filePath);
  63. stringbuilder.replace(0, FileConstants.fileVirtualPath.length(), FileConstants.fileLinuxPath);
  64. realPath = stringbuilder.toString();
  65. }
  66. }
  67. return realPath;
  68. }
  69. public void fileUpload(HttpServletRequest request) throws IOException {
  70. CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
  71. if (multipartResolver.isMultipart(request)) {
  72. MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
  73. Iterator<String> iterator = multiRequest.getFileNames();
  74. while (iterator.hasNext()) {
  75. // 上传的文件
  76. MultipartFile item = multiRequest.getFile(iterator.next());
  77. if (item != null) {
  78. log.info("文件名:" + item.getOriginalFilename());
  79. log.info("文件类型:" + item.getContentType());
  80. log.info("文件大小:" + item.getSize());
  81. // 文件的原始名称
  82. String originalFilename = item.getOriginalFilename();
  83. String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
  84. // 如果名称不为“”,说明该文件存在,否则说明该文件不存在
  85. if (!"".equals(originalFilename.trim())) {
  86. String newFileName = UUID.randomUUID() + ext;
  87. String filePath = getUploadRealPath();
  88. //不是图片,直接保存
  89. item.transferTo(new File(filePath, newFileName));
  90. }
  91. }
  92. }
  93. }
  94. }
  95. public String fileDownload(HttpServletResponse response, String fileName, String filePath) throws IOException {
  96. log.info("当前下载文件名为: {}",fileName);
  97. log.info("当前下载文件目录: {}",filePath);
  98. // 获取文件的真实存储路径
  99. String realPath = getDownloadRealPath(filePath);
  100. File file = new File(realPath);
  101. if(file.exists()){
  102. // 将文件读取为文件输入流
  103. FileInputStream is = new FileInputStream(file);
  104. // 获取响应流之前 一定要设置以附件形式下载 attachment:附件
  105. response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
  106. // 获取响应输出流
  107. ServletOutputStream os = response.getOutputStream();
  108. // 输入流复制给输出流
  109. /*int len=0;
  110. byte[] b = new byte[1024];
  111. while(true){
  112. len = is.read(b);
  113. if(len==-1) break;
  114. os.write(b,0,len);
  115. }*/
  116. FileCopyUtils.copy(is,os);
  117. log.info("文件下载成功!");
  118. } else {
  119. return "文件不存在";
  120. }
  121. return "文件下载成功!";
  122. }
  123. }

为了区别于下载时获取屋里路径的方法getDownloadRealPath(),这里将上传时获取真实路径的方法改成了getUploadRealPath()

4.测试

4.1 windows下

我们启动项目,在浏览器访问http://localhost:8807/download.jsp,然后在界面中点击睡美人-windows下载图片(这里不要点击linux下的),注意观察界面与控制台。如下图所示:

4.2 linux下

我们重新打包当前项目,传至linux服务器上,执行命令java -jar springboot-07-file-0.0.1-SNAPSHOT.jar重新启动该项目。如下图所示:

然后浏览器访问http://192.168.8.100:8807/download.jsp,点击睡美人-linux,注意观察页面和控制台。如下图所示:

《新程序员》:云原生和全面数字化实践

50位技术专家共同创作,文字、视频、音频交互阅读

相关文章