Java课程实验 Spring Boot 文件上传与下载

简介: Java课程实验 Spring Boot 文件上传与下载

一、实验目的

1.文件上传

2.文件下载

二、实验内容

1.掌握 Spring Boot 中 MVC 功能的定制和扩展

2.掌握 Spring Boot 整合 Servlet 三大组件的实现

3.掌握 Spring Boot 文件上传与下载的实现

三、实验步骤及截图

1.使用Idea+Maven新建项目,并对Idea必要配置。

2.导入数据库,配置POM.xml引入commons-io等必要包。

3.编写 全局配置文件 application.properties,配置上传下载参数等。

4.编写入口类。

1. @EnableCaching
2. 
3. @ServletComponentScan
4. 
5. @SpringBootApplication
6. 
7. public class Chapter04MySQL {
8. 
9.     public static void main(String[] args) {
10. 
11.         SpringApplication.run(Chapter04MySQL.class);
12. 
13.     }
14. 
15. }

5.编写controller类,实现文件上传功能。

1. @Controller
2. 
3. public class FileController {
4. 
5.     String pathParent = "G:/File";
6. 
7.     //向文件上传页面跳转
8. 
9.     @GetMapping("/toUpload")
10. 
11.     public String toUpload(){
12. 
13.         return "file/upload";
14. 
15.     }
16. 
17.     //文件上传管理
18. 
19.     @PostMapping("/uploadFile")
20. 
21.     public String uploadFile(MultipartFile[] fileUpload, Model model) {
22. 
23.         //上传成功返回状态信息
24. 
25.         model.addAttribute("uploadStatus", "上传成功!");
26. 
27.         for (MultipartFile file : fileUpload) {
28. 
29.             //获取文件名以及后缀名
30. 
31.             String fileName = file.getOriginalFilename();
32. 
33.             //重新生成文件名
34. 
35.             fileName = UUID.randomUUID()+"_"+fileName;
36. 
37.             //指定上传文件本地存储目录,不存在则需创建
38. 
39.             String dirPath = pathParent+"/upload/";
40. 
41.             File filePath = new File(dirPath);
42. 
43.             if(!filePath.exists()){
44. 
45.                 filePath.mkdirs();
46. 
47.             }
48. 
49.             try {
50. 
51.                 file.transferTo(new File(dirPath+fileName));
52. 
53.             } catch (Exception e) {
54. 
55.                 e.printStackTrace();
56. 
57.                 //上传失败返回失败信息
58. 
59.                 model.addAttribute("uploadStatus","上传失败: "+e.getMessage());
60. 
61.             }
62. 
63.         }
64. 
65.         //携带上传状态信息回调到文件上传页面
66. 
67.         return "file/upload";
68. 
69.     }
70. 
71. }

6.编写controller类,实现文件下载功能。

1. //向文件下载页面跳转
2. 
3.     @GetMapping("/toDownload")
4. 
5.     public String toDownload(){
6. 
7.         return "file/download";
8. 
9.     }
10. 
11. 
12. 
13.     @GetMapping("/download")
14. 
15.     //所有类型文件下载管理
16. 
17.     public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, String filename) throws Exception{
18. 
19.         //指定要下载的文件根路径
20. 
21.         String dirPath = pathParent+"/download/";
22. 
23.         //创建该文件对象
24. 
25.         File file = new File(dirPath + File.separator + filename);
26. 
27.         //设置响应头
28. 
29.         HttpHeaders headers = new HttpHeaders();
30. 
31.         //通知浏览器已下载方式打开(下载前对文件名进行转码)
32. 
33.         filename=getFilename(request,filename);
34. 
35.         headers.setContentDispositionFormData("attachment",filename);
36. 
37.         //定义以流的方式下载返回文件数据
38. 
39.         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
40. 
41.         try {
42. 
43.             return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
44. 
45.         } catch (Exception e) {
46. 
47.             e.printStackTrace();
48. 
49.             return new ResponseEntity<byte[]>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
50. 
51.         }
52. 
53.     }

7.编写前端页面,实现文件上传页面。

1. <!DOCTYPE html>
2. 
3. <html lang="en" xmlns:th="http://www.thymeleaf.org">
4. 
5. <head>
6. 
7.     <meta charset="UTF-8">
8. 
9.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
10. 
11.     <title>文件上传</title>
12. 
13.     <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
14. 
15.     <script th:src="@{/login/js/jquery.min.js}"></script>
16. 
17. </head>
18. 
19. <body>
20. 
21. <div th:if="${uploadStatus}" style="color: red" th:text="${uploadStatus}">上传成功</div>
22. 
23. <form th:action="@{/uploadFile}" method="post" enctype="multipart/form-data">上传文件:&nbsp;&nbsp;
24. 
25.     <input type="button" value="添加文件" onclick="add()"/>
26. 
27.     <div id="file" style="margin-top: 10px;" th:value="上传区域"></div>
28. 
29.     <input id="submit" type="submit" value="文件上传" style="display: none;margin-top: 10px;"/>
30. 
31. </form>
32. 
33. <script type="text/javascript">
34. 
35.     function add() {
36. 
37.         var innerdiv = "<div>";
38. 
39.         innerdiv += "<input type='file' name='fileUpload' required='required'>"+
40. 
41.                     "<input type='button' value='删除' onclick='remove(this)'>";
42. 
43.         innerdiv += "<div>";
44. 
45.         $("#file").append(innerdiv);
46. 
47.         $("#submit").css("display","block");
48. 
49.     }
50. 
51.     //删除当前行
52. 
53.     function remove(obj) {
54. 
55.         $(obj).parent().remove();
56. 
57.         if ($("#file div").length == 0){
58. 
59.             $("#submit").css("display","none");
60. 
61.         }
62. 
63.     }
64. 
65. </script>
66. 
67. </body>
68. 
69. </html>

8.编写前端页面,实现文件下载页面。

1.  <!DOCTYPE html>
2. 
3. <html lang="en" xmlns:th="http://www.thymeleaf.org">
4. 
5. <head>
6. 
7.     <meta charset="UTF-8">
8. 
9.     <title>文件下载</title>
10. 
11. </head>
12. 
13. <body>
14. 
15. <div style="margin-bottom: 10px">文件下载列表:</div>
16. 
17. <table>
18. 
19.     <tr>
20. 
21.         <td>bloglogo.jpg</td>
22. 
23.         <td><a th:href="@{/download(filename='bloglogo.jpg')}">下载文件</a > </td>
24. 
25.     </tr>
26. 
27.     <tr>
28. 
29.         <td>第5章 SpringBoot实现Web开发.ppt</td>
30. 
31.         <td><a th:href="@{/download(filename='第5章 SpringBoot实现Web开发.ppt')}">下载文件</a > </td>
32. 
33.     </tr>
34. 
35. </table>
36. 
37. </body>
38. 
39. </html>

9.编写controller类,实现中文文件名文件下载功能。

1. //根据浏览器的不同编码设置,返回编码的文件名
2. 
3.     private String getFilename(HttpServletRequest request, String filename)
4. 
5.             throws Exception {
6. 
7.         //IE不同版本User-Agent中出现的关键字
8. 
9.         String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
10. 
11.         //获取请求头代理信息
12. 
13.         String userAgent = request.getHeader("User-Agent");
14. 
15.         for (String keyWord : IEBrowserKeyWords) {
16. 
17.             if (userAgent.contains(keyWord)) {
18. 
19.                 //IE内核浏览器,统一为UTF-8编码显示,并对转换的+进行更正
20. 
21.                 return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
22. 
23.             }
24. 
25.         }
26. 
27.         //火狐等其他浏览器统一为ISO-8859-1编码显示
28. 
29.         return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
30. 
31.     }

四、实验中遇到的问题及采取的措施(10分)

报错1:org.thymeleaf.exceptions.TemplateInputException: Error resolving template [file/download], template might not exist or might not be accessible by any of the configured Template Resolvers。

排错过程1:

第一步,检查templates是否放在resource下面。

第二步,检查templates是否拼写有误。

原因分析1:

这个错误信息是Thymeleaf模板引擎报错,通常是因为找不到指定的模板文件。你需要检查一下你的文件路径和文件名是否正确,确保模板文件存在于你指定的位置,并且有足够的读取权限。同时,你还需要确定你所使用的 Template Resolver 配置是正确的,能够解析出你的模板文件。

注:由于源码量过多,需要的朋友可在资源中下载,也可私信我拿取!

目录
相关文章
|
4天前
|
人工智能 自然语言处理 Java
Spring AI,Spring团队开发的新组件,Java工程师快来一起体验吧
文章介绍了Spring AI,这是Spring团队开发的新组件,旨在为Java开发者提供易于集成的人工智能API,包括机器学习、自然语言处理和图像识别等功能,并通过实际代码示例展示了如何快速集成和使用这些AI技术。
Spring AI,Spring团队开发的新组件,Java工程师快来一起体验吧
|
1天前
|
前端开发 IDE Java
"揭秘前端转Java的秘径:SpringBoot Web极速入门,掌握分层解耦艺术,让你的后端代码飞起来,你敢来挑战吗?"
【8月更文挑战第19天】面向前端开发者介绍Spring Boot后端开发,通过简化Spring应用搭建,快速实现Web应用。本文以创建“Hello World”应用为例,展示项目基本结构与运行方式。进而深入探讨三层架构(Controller、Service、DAO)下的分层解耦概念,通过员工信息管理示例,演示各层如何协作及依赖注入的使用,以此提升代码灵活性与可维护性。
|
1天前
|
安全 前端开发 Java
随着企业应用复杂度提升,Java Spring框架以其强大与灵活特性简化开发流程,成为构建高效、可维护应用的理想选择
随着企业应用复杂度提升,Java Spring框架以其强大与灵活特性简化开发流程,成为构建高效、可维护应用的理想选择。依赖注入使对象管理交由Spring容器处理,实现低耦合高内聚;AOP则分离横切关注点如事务管理,增强代码模块化。Spring还提供MVC、Data、Security等模块满足多样需求,并通过Spring Boot简化配置与部署,加速微服务架构构建。掌握这些核心概念与工具,开发者能更从容应对挑战,打造卓越应用。
7 1
|
5天前
|
Java
Java SpringBoot 7z 压缩、解压
Java SpringBoot 7z 压缩、解压
16 1
|
5天前
|
Java API 开发者
JDK8到JDK17版本升级的新特性问题之SpringBoot选择JDK17作为最小支持的Java lts版本意味着什么
JDK8到JDK17版本升级的新特性问题之SpringBoot选择JDK17作为最小支持的Java lts版本意味着什么
JDK8到JDK17版本升级的新特性问题之SpringBoot选择JDK17作为最小支持的Java lts版本意味着什么
|
5天前
|
Java 知识图谱
知识图谱(Knowledge Graph)- Neo4j 5.10.0 使用 - Java SpringBoot 操作 Neo4j
知识图谱(Knowledge Graph)- Neo4j 5.10.0 使用 - Java SpringBoot 操作 Neo4j
13 0
|
5天前
|
Java 测试技术 Spring
Java SpringBoot 加载 yml 配置文件中字典项
Java SpringBoot 加载 yml 配置文件中字典项
10 0
|
5天前
|
Java Spring 容器
Java SpringBoot 中,动态执行 bean 对象中的方法
Java SpringBoot 中,动态执行 bean 对象中的方法
14 0
|
5天前
|
前端开发 Java
如何实现 Java SpringBoot 自动验证入参数据的有效性
如何实现 Java SpringBoot 自动验证入参数据的有效性
15 0
|
1天前
|
JavaScript Java Maven
毕设项目&课程设计&毕设项目:springboot+vue实现的在线求职管理平台(含教程&源码&数据库数据)
本文介绍了一款基于Spring Boot和Vue.js实现的在线求职平台。该平台采用了前后端分离的架构,使用Spring Boot作为后端服务
毕设项目&课程设计&毕设项目:springboot+vue实现的在线求职管理平台(含教程&源码&数据库数据)