在 Spring Boot 中实现文件下载功能

发布于:2024-06-13 ⋅ 阅读:(156) ⋅ 点赞:(0)

文件下载是许多 Web 应用程序中的常见需求。在这篇博客文章中,我们将展示如何使用 Spring Boot 实现文件下载功能。我们将使用一个简单的示例,展示如何从服务器下载音频文件(MP3)。

项目设置

首先,我们需要创建一个新的 Spring Boot 项目。如果您还没有创建项目,可以使用 Spring Initializr 创建一个新的 Spring Boot 项目,并添加以下依赖项:

  • Spring Web

创建自定义的 MediaType

在处理文件下载时,我们需要正确设置文件的 MIME 类型。对于 MP3 文件,MIME 类型是 audio/mpeg。我们可以创建一个自定义的 MediaType 来表示这一点。

import org.springframework.http.MediaType;

public class CustomMediaTypes {
    public static final MediaType AUDIO_MP3 = MediaType.parseMediaType("audio/mpeg");
}

创建控制器

接下来,我们将创建一个控制器,用于处理文件下载请求。控制器将根据请求的文件名从服务器的特定目录中读取文件,并将其作为响应返回给客户端。

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

@RestController
public class AudioStreamController {

    @GetMapping("/audio/{filename}")
    public ResponseEntity<InputStreamResource> streamAudio(@PathVariable String filename) {
        File file = new File("path/to/your/audio/" + filename);

        try {
            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));

            // 根据文件扩展名设置 MIME 类型
            String contentType = determineMediaType(filename);
            if (contentType == null) {
                return ResponseEntity.unsupportedMediaType().build();
            }

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(resource);

        } catch (FileNotFoundException e) {
            return ResponseEntity.notFound().build();
        }
    }

    private String determineMediaType(String filename) {
        if (filename.endsWith(".mp3")) {
            return CustomMediaTypes.AUDIO_MP3.toString();
        }
        // 添加其他需要支持的音频 MIME 类型
        return null;
    }
}

代码解释

  1. 控制器方法

    • @GetMapping("/audio/{filename}"):定义了一个 GET 请求的端点,用于下载音频文件。
    • determineMediaType 方法根据文件扩展名返回相应的 MIME 类型。
  2. 响应设置

    • 设置 Content-Length 头,指示文件的长度。
    • 设置 Content-Type 头为 audio/mpeg,以确保浏览器正确处理 MP3 文件。

测试文件下载

假设您的应用程序运行在 http://localhost:8080,并且音频文件名为 example.mp3,您可以通过以下 URL 直接在浏览器中下载音频文件:

http://localhost:8080/audio/example.mp3

当您访问上述 URL 时,浏览器将提示您下载该文件。

总结

在这篇博客文章中,我们展示了如何在 Spring Boot 应用中实现文件下载功能。通过定义自定义的 MediaType 对象,我们可以灵活地处理各种 MIME 类型,包括 MP3 文件。希望这篇文章对您有所帮助,能够让您在自己的项目中轻松实现文件下载功能。


网站公告

今日签到

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