1. 文件上传

1.1. pom.xml引入依赖

<!-- 文件上传 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.6</version>
</dependency>

1.2. 编写controller

@RestController
public class FileController {
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "文件为空";
        }
        String fileName = file.getOriginalFilename();
        String filePath = "D:/upload/";
        File dest = new File(filePath + fileName);
        file.transferTo(dest);
        return "上传成功";
    }
}

1.3. 编写前端页面

<form action="/upload" method="post" enctype="multipart/form-data">
   <input type="file" name="file" />
   <input type="submit" value="上传" />
</form>
  1. 文件下载

2.1. pom.xml引入依赖

<!-- 文件下载 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2. 编写controller

@RestController
public class FileController {
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        String fileName = "file.txt";
        String filePath = "D:/upload/";
        File file = new File(filePath + fileName);
        InputStream inputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
    }
}

2.3. 编写前端页面

<a href="/download">下载文件</a>

注意:文件下载需要设置response的Content-Disposition为attachment,否则文件将在浏览器中直接打开

Spring Boot实现文件上传下载

原文地址: https://www.cveoy.top/t/topic/g5wd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录