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

 

 

 

 

 

 

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐