SpringBoot2.X实现文件上传与下载

本例子基于spring-boot-2.1.6.RELEASE开发
pom文件:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <!--spring-boot-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
     </dependencies>

springboot对于文件上传的yml配置

spring:
  servlet:
    multipart:
      max-file-size: 2MB #上传一个文件最大值 默认是1MB
      max-request-size: 20MB #上传多个文件最大值  默认是10MB

直接上代码

import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping(path = "/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class FileController {
    final String path = "D:\\tmp\\";

    final String fileName = "D:\\tmp\\你好.txt";

    //文件上传
    @PostMapping(path = "/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
    	//获取原始文件名
        String originalFilename = file.getOriginalFilename();
        File localFile = new File(path + originalFilename);
        try {
        	//直接将文件拷贝到指定位置
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (localFile.exists()) {
            return "ok";
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return "error";
        }
    }

    //批量文件上传
    @PostMapping(path = "/uploads")
    public String uploadFiles(@RequestParam("file") MultipartFile[] files, HttpServletResponse response) {
        boolean result = true;
        StringBuilder stringBuilder = new StringBuilder();
        for (MultipartFile file : files) {
        	//获取原始文件名
            String originalFilename = file.getOriginalFilename();
            File localFile = new File(path + originalFilename);
            try {
            	//直接将文件拷贝到指定位置
                file.transferTo(localFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            boolean exists = localFile.exists();
            if (!exists) {
                result = false;
                stringBuilder.append(file.getOriginalFilename()).append(" ");
            }
        }
        if (result) {
            return "ok";
        }
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return "upload fail, file name : " + stringBuilder.toString();
    }

    //文件下载
    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response) {
        File file = new File(fileName);
        if (file.exists()) {
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis)) {
                response.setContentType("application/force-download");
                //保证下载时文件名为指定文件名,避免中文文件名乱码
                response.addHeader("Content-Disposition", "attachment;fileName="
                        + URLEncoder.encode(file.getName(), "utf-8"));
                OutputStream os = response.getOutputStream();
                StreamUtils.copy(bis, os);
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                e.printStackTrace();
            }
        }
    }
}

测试上传单个文件
单个文件 上传
测试上传多个文件
多个文件上传
下载文件测试直接使用浏览器请求接口URL即可

对于通过SpringCloudZuul映射后的文件上传请求,在文件上传时请求的url中需要加上/zuul前缀才能保证中文不乱码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了一些方便的类和方法来实现文件上传下载。下面分别介绍如何实现文件上传文件下载。 ## 文件上传 ### 1. 引入依赖 在 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 添加文件上传依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> ``` ### 2. 配置文件上传路径 在 `application.properties` 文件中添加以下配置: ```properties # 上传文件保存目录 spring.servlet.multipart.location=上传文件保存目录 # 文件上传限制 spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` ### 3. 编写文件上传接口 在控制器中编写文件上传接口: ```java @RestController public class FileController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { // 获取上传文件名 String fileName = file.getOriginalFilename(); // 保存上传文件 file.transferTo(new File("上传文件保存目录/" + fileName)); return "上传成功!"; } } ``` ### 4. 测试文件上传 启动应用后,使用 `curl` 命令或者浏览器访问 `http://localhost:8080/upload` 接口进行文件上传,例如: ```bash curl -X POST -F file=@/path/to/file http://localhost:8080/upload ``` ## 文件下载 ### 1. 编写文件下载接口 在控制器中编写文件下载接口: ```java @RestController public class FileController { @GetMapping("/download") public ResponseEntity<Resource> downloadFile(@RequestParam("fileName") String fileName) throws IOException { // 获取文件流 InputStreamResource resource = new InputStreamResource(new FileInputStream("文件保存目录/" + fileName)); // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=" + fileName); // 返回文件流 return ResponseEntity.ok() .headers(headers) .contentLength(resource.contentLength()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); } } ``` ### 2. 测试文件下载 启动应用后,使用 `curl` 命令或者浏览器访问 `http://localhost:8080/download?fileName=文件名` 接口进行文件下载,例如: ```bash curl -OJL http://localhost:8080/download?fileName=example.txt ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值