springboot实现文件下载接口

 

1. 导入依赖

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

 

2. controller接口实现

就几行代码,分析一下,根据自己的需要改动,只要拿到文件流,其他的都很简单

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.nio.charset.StandardCharsets;

@RestController
public class DowFile {

    @GetMapping("/file")
    public ResponseEntity<byte[]> doReport() {
        try {
            File file = new File("D://11.jpg");

            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment",
                    new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1"));
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 获取文件的字节数组 - 需要使用commons-io依赖包
            byte[] content = FileUtils.readFileToByteArray(file);
            return new ResponseEntity<>(content, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

 

 

3、设置上传文件的大小配置

需要设置以下两个参数,不同的版本对应不同的键值,需对应版本

Spring Boot 1.3.x或者之前

multipart.maxFileSize=100Mb
multipart.maxRequestSize=1000Mb

Spring Boot 1.4.x

spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=1000Mb

  很多人设置了multipart.maxFileSize但是不起作用,是因为1.4版本以上的配置改了,详见官方文档:spring boot 1.4

Spring Boot 2.0之后

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB

 

 

如果使用的是FTP服务器可以参考:https://blog.csdn.net/weixin_40516924/article/details/109377030

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ark方舟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值