要开发一个可以通过播放器播放但客户端无法直接下载的blob接口,可以按照以下步骤进行实现:

  1. 创建一个Java类,命名为BlobController。
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class BlobController {

    @GetMapping("/blob")
    public ResponseEntity<InputStreamResource> getBlob() throws IOException {
        // 读取mp4文件的输入流
        InputStream inputStream = new FileInputStream("path/to/your/file.mp4");

        // 创建一个HttpHeaders对象,设置Content-Disposition为inline,表示在浏览器中播放而非下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("inline", "file.mp4");

        // 设置Content-Type为video/mp4
        headers.setContentType(MediaType.valueOf("video/mp4"));

        // 创建一个InputStreamResource对象,将输入流和headers传入
        InputStreamResource resource = new InputStreamResource(inputStream);

        // 返回ResponseEntity,将resource和headers传入构造函数
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
}
  1. 配置Spring Boot应用的依赖和启动类。

在pom.xml文件中添加以下依赖:

<dependencies>
    <!-- 其他依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

创建一个Spring Boot的启动类,命名为Application:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 启动Spring Boot应用。

运行Application的main方法,启动Spring Boot应用。

  1. 测试接口。

通过浏览器访问http://localhost:8080/blob,应该能够在浏览器中播放mp4文件,但无法直接下载。


原文地址: https://www.cveoy.top/t/topic/pIzJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录