Spring-Boot实现HTTP大文件断点续传分片下载
服务端如何将一个大视频文件做切分,分段响应给客户端,让浏览器可以渐进式地播放。
Spring Boot实现HTTP分片下载断点续传,从而实现H5页面的大视频播放问题,实现渐进式播放,每次只播放需要播放的内容就可以了,不需要加载整个文件到内存中。
文件的断点续传、文件多线程并发下载(迅雷就是这么玩的)等。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-bom</artifactId>
<version>5.8.18</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
代码实现
ResourceController
package com.example.insurance.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import com.example.insurance.common.ContentRange;
import com.example.insurance.common.MediaContentUtil;
import com.example.insurance.common.NioUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRange;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 内容资源控制器
*/
@SuppressWarnings("unused")
@Slf4j
@RestController("resourceController")
@RequestMapping(path = "/resource")
public class ResourceController {
/**
* 获取文件内容
*
* @param fileName 内容文件名称
* @param response 响应对象
*/
@GetMapping("/media/{fileName}")
public void getMedia(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response,
@RequestHeader HttpHeaders headers) {
// printRequestInfo(fileName, request, headers);
String filePath = MediaContentUtil.filePath();
try {
this.download(fileName, filePath, request, response, headers);
} catch (Exception e) {
log.error("getMedia error, fileName={}", fileName, e);
}
}
/**
* 获取封面内容
*
* @param fileName 内容封面名称
* @param response 响应对象
*/
@GetMapping("/cover/{fileName}")
public void getCover