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.编写入口类。

@EnableCaching

@ServletComponentScan

@SpringBootApplication

public class Chapter04MySQL {

    public static void main(String[] args) {

        SpringApplication.run(Chapter04MySQL.class);

    }

}

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

@Controller

public class FileController {

    String pathParent = "G:/File";

    //向文件上传页面跳转

    @GetMapping("/toUpload")

    public String toUpload(){

        return "file/upload";

    }

    //文件上传管理

    @PostMapping("/uploadFile")

    public String uploadFile(MultipartFile[] fileUpload, Model model) {

        //上传成功返回状态信息

        model.addAttribute("uploadStatus", "上传成功!");

        for (MultipartFile file : fileUpload) {

            //获取文件名以及后缀名

            String fileName = file.getOriginalFilename();

            //重新生成文件名

            fileName = UUID.randomUUID()+"_"+fileName;

            //指定上传文件本地存储目录,不存在则需创建

            String dirPath = pathParent+"/upload/";

            File filePath = new File(dirPath);

            if(!filePath.exists()){

                filePath.mkdirs();

            }

            try {

                file.transferTo(new File(dirPath+fileName));

            } catch (Exception e) {

                e.printStackTrace();

                //上传失败返回失败信息

                model.addAttribute("uploadStatus","上传失败: "+e.getMessage());

            }

        }

        //携带上传状态信息回调到文件上传页面

        return "file/upload";

    }

}

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

//向文件下载页面跳转

    @GetMapping("/toDownload")

    public String toDownload(){

        return "file/download";

    }



    @GetMapping("/download")

    //所有类型文件下载管理

    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, String filename) throws Exception{

        //指定要下载的文件根路径

        String dirPath = pathParent+"/download/";

        //创建该文件对象

        File file = new File(dirPath + File.separator + filename);

        //设置响应头

        HttpHeaders headers = new HttpHeaders();

        //通知浏览器已下载方式打开(下载前对文件名进行转码)

        filename=getFilename(request,filename);

        headers.setContentDispositionFormData("attachment",filename);

        //定义以流的方式下载返回文件数据

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        try {

            return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);

        } catch (Exception e) {

            e.printStackTrace();

            return new ResponseEntity<byte[]>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);

        }

    }

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

<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>文件上传</title>

    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">

    <script th:src="@{/login/js/jquery.min.js}"></script>

</head>

<body>

<div th:if="${uploadStatus}" style="color: red" th:text="${uploadStatus}">上传成功</div>

<form th:action="@{/uploadFile}" method="post" enctype="multipart/form-data">上传文件:&nbsp;&nbsp;

    <input type="button" value="添加文件" onclick="add()"/>

    <div id="file" style="margin-top: 10px;" th:value="上传区域"></div>

    <input id="submit" type="submit" value="文件上传" style="display: none;margin-top: 10px;"/>

</form>

<script type="text/javascript">

    function add() {

        var innerdiv = "<div>";

        innerdiv += "<input type='file' name='fileUpload' required='required'>"+

                    "<input type='button' value='删除' onclick='remove(this)'>";

        innerdiv += "<div>";

        $("#file").append(innerdiv);

        $("#submit").css("display","block");

    }

    //删除当前行

    function remove(obj) {

        $(obj).parent().remove();

        if ($("#file div").length == 0){

            $("#submit").css("display","none");

        }

    }

</script>

</body>

</html>

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

 <!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>

    <meta charset="UTF-8">

    <title>文件下载</title>

</head>

<body>

<div style="margin-bottom: 10px">文件下载列表:</div>

<table>

    <tr>

        <td>bloglogo.jpg</td>

        <td><a th:href="@{/download(filename='bloglogo.jpg')}">下载文件</a > </td>

    </tr>

    <tr>

        <td>第5章 SpringBoot实现Web开发.ppt</td>

        <td><a th:href="@{/download(filename='第5章 SpringBoot实现Web开发.ppt')}">下载文件</a > </td>

    </tr>

</table>

</body>

</html>

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

//根据浏览器的不同编码设置,返回编码的文件名

    private String getFilename(HttpServletRequest request, String filename)

            throws Exception {

        //IE不同版本User-Agent中出现的关键字

        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};

        //获取请求头代理信息

        String userAgent = request.getHeader("User-Agent");

        for (String keyWord : IEBrowserKeyWords) {

            if (userAgent.contains(keyWord)) {

                //IE内核浏览器,统一为UTF-8编码显示,并对转换的+进行更正

                return URLEncoder.encode(filename, "UTF-8").replace("+"," ");

            }

        }

        //火狐等其他浏览器统一为ISO-8859-1编码显示

        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");

    }

四、实验中遇到的问题及采取的措施(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 配置是正确的,能够解析出你的模板文件。

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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Meteor.792

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值