springboot之文件上传下载

springboot 版本2.7.4

依赖

		<!-- 可以不导入thymeleaf,因测试引入 -->
 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

application.yaml

spring:
  servlet:
    multipart:
      enabled: true # 表示是否开启文件上传支持,默认为 true
      file-size-threshold: 0 # 表示文件写入磁盘的阀值,默认为 0
      location: # 表示上传文件的临时保存位置
      max-file-size: 1MB # 表示上传的单个文件的最大大小,默认为 1MB
      max-request-size: 10MB # 表示多文件上传时文件的总大小,默认为 10MB

controller

package com.tcoding.demo.file.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class IndexController {

    @GetMapping
    public String index() {
        return "index";
    }

    @ResponseBody
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 设置文件存储路径
        // 因为测试,就放在classpath下。正式环境是要存在文件服务器上
        try {
            String filePath = new ClassPathResource("/").getURI().getPath();
            String path = filePath + fileName;
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                // 新建文件夹
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            // 文件写入
            return "上传成功";
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }

        return "上传失败";
    }

    @ResponseBody
    @PostMapping("/batch")
    public String handleFileUpload(HttpServletRequest request) throws IOException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            String filePath = new ClassPathResource("/").getURI().getPath();
            if (!file.isEmpty()) {
                try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(filePath + file.getOriginalFilename()));) {
                    byte[] bytes = file.getBytes();
                    // 写入
                    stream.write(bytes);
                } catch (Exception e) {
                    return "第 " + i + " 个文件上传失败 ==> " + e.getMessage();
                }
            } else {
                return "第 " + i + " 个文件上传失败因为文件为空";
            }
        }
        return "上传成功";
    }

    @ResponseBody
    @GetMapping("/download")
    public String downloadFile(HttpServletResponse response) throws IOException {
        String fileName = "test.svg";
        //设置文件路径
        String filePath = new ClassPathResource("/").getURI().getPath();
        File file = new File(filePath + fileName);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];

            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "下载失败";
    }
}


test

resources/templates 下创建 index,html文件

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<p>单文件上传</p>
<form action="upload" method="POST" enctype="multipart/form-data">
  文件:<input type="file" name="file"/>
  <input type="submit"/>
</form>
<hr/>
<p>文件下载</p>
<a href="download">下载文件</a>
<hr/>
<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data" action="batch">
  <p>文件1:<input type="file" name="file"/></p>
  <p>文件2:<input type="file" name="file"/></p>
  <p><input type="submit" value="上传"/></p>
</form>
</body>
</html>

源码地址

https://github.com/googalAmbition/hello-spring-boot/tree/main/49-file

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

tcoding

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

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

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

打赏作者

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

抵扣说明:

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

余额充值