SpringBoot 上传下载文件

1. pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.6.3</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.15.0</version>
</dependency>

2. application.yml

spring:
  servlet:
    multipart:
      max-request-size: 500MB
      max-file-size: 500MB

3. 创建接口类

import org.apache.commons.io.FileUtils;
import org.springframework.http.ContentDisposition;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
public class FileController {

    /**
     * 文件上传到服务器
     */
    @PostMapping(value = "/upload", produces = MediaType.APPLICATION_JSON_VALUE)
    public void upload(@RequestPart("file") MultipartFile file) {
        try {
            String filePath = "d:/" + file.getOriginalFilename();
            File writeFile = new File(filePath);
            FileUtils.copyInputStreamToFile(file.getInputStream(), writeFile);
            // TODO: 文件上传后自定义处理
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 本地文件下载到客户端
     */
    @PostMapping(value = "/down", produces = MediaType.APPLICATION_JSON_VALUE)
    public void down(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        InputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            // TODO: 文件在服务器中的绝对路径
            String filePath = "d:/" + fileName;
            inputStream = new FileInputStream(filePath);
            response.reset();

            response.addHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
            ContentDisposition disposition = ContentDisposition.builder("attachment")
                    .filename(new String(URLEncoder.encode(fileName, "UTF-8")
                            .getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)).build();
            response.addHeader("Content-Disposition", disposition.toString());

            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 网络文件下载到客户端
     */
    @PostMapping(value = "/netDown", produces = MediaType.APPLICATION_JSON_VALUE)
    public void netDown(@RequestParam("net") String net, @RequestParam("fileName") String fileName, HttpServletResponse response) {
        InputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            URL url = new URL(net);
            URLConnection connection = url.openConnection();
            inputStream = connection.getInputStream();
            response.reset();

            response.addHeader("Content-Type", connection.getContentType());
            ContentDisposition disposition = ContentDisposition.builder("attachment")
                    .filename(new String(URLEncoder.encode(fileName, "UTF-8")
                            .getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)).build();
            response.addHeader("Content-Disposition", disposition.toString());

            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}