Springboot 文件下载

发布于:2025-02-24 ⋅ 阅读:(82) ⋅ 点赞:(0)

文件下载


添加依赖:通常,文件下载功能不需要额外的依赖,但确保你的pom.xml或build.gradle文件中包含Spring Web依赖。

<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 其他依赖 -->
</dependencies>
package com.sh.system.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/files")
public class FileController {

    // 从服务器文件系统下载文件
    @GetMapping("/download/server")
    public ResponseEntity<byte[]> downloadFromServer(HttpServletResponse response) throws IOException {
        Path filePath = Paths.get("D:\\测试下载.docx");
        byte[] data = Files.readAllBytes(filePath);
        //
        String originalFileName = filePath.getFileName().toString();
        String fileName = new String(originalFileName.getBytes("UTF-8"), "ISO-8859-1");
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(data.length)
                .body(data);
    }



    // 从类路径下下载文件
    @GetMapping("/download/classpath")
    public ResponseEntity<Resource> downloadFromClasspath(HttpServletResponse response) throws IOException {
        Resource resource = new ClassPathResource("static/deepSeek说明.docx");
        String originalFileName = resource.getFilename();
        String fileName = new String(originalFileName.getBytes("UTF-8"), "ISO-8859-1");
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
}


放置测试文件:
如果你选择从类路径下载文件,将文件(例如example.txt)放在src/main/resources/static/目录下。
如果你选择从服务器文件系统下载文件,确保文件路径正确,并且Spring Boot应用有权限访问该文件。
运行应用:启动Spring Boot应用,并访问以下URL测试文件下载功能:
类路径文件下载:http://localhost:8080/files/download/classpath
服务器文件系统文件下载:http://localhost:8080/files/download/server


网站公告

今日签到

点亮在社区的每一天
去签到