springboot3.1.5+文件上传+文件下载

发布时间 2023-11-09 09:43:43作者: MaoShine

idea创建项目springbootdemo-download-upload

  • 加上thymeleaf模板maven依赖
  • application.properties配置
# thymeleaf页面缓存设置(默认为true)
spring.thymeleaf.cache=false
# 单个上传文件大小限制(默认1MB)
spring.servlet.multipart.max-file-size=10MB
# 总上传文件大小限制(默认10MB)
spring.servlet.multipart.max-request-size=50MB

文件上传前端表单upload.html

<!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 href="css/bootstrap.min.css" rel="stylesheet">
  <script src="js/jquery-3.4.1.js"></script>
  <script>
    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>
</head>
<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>
</body>
</html>

文件上传后端springboot的controller

@RequestMapping("/toUpload")
    public String toUpload(){
        return "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 = "C:/Users/Desktop/";//需要自己写
            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 "upload";
    }

文件下载

  • 添加文件下载的FileUtils工具类
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

前端下载

<!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>9010094_s.jpg</td>
        <td><a th:href="@{/download(filename='9010094_s.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>

springboot后端controller路由

@RequestMapping("/todownload")
    public String todownload(){
        return "download";
    }

    // 文件下载管理
    // 这个是比较简单的接受下载,没有中文编码的处理
    @GetMapping("/ddownload")
    public ResponseEntity<byte[]> fileDownload(String filename){
        // 指定要下载的文件根路径
        String dirPath = "C:\\Users\\Desktop/";
        // 创建该文件对象
        File file = new File(dirPath + File.separator + filename);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 通知浏览器以下载方式打开
        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);
        }
    }


    // 所有类型文件下载管理
    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,
                                               String filename) throws Exception{
        // 指定要下载的文件根路径
        String dirPath = "C:/Users/Desktop/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);
        }
    }
    // 根据浏览器的不同进行编码设置,返回编码后的文件名
    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");
    }