You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome中React HTML5视频无法加载问题的解决方法

问题解决:Chrome无法加载FastAPI流式视频的修复方案

问题核心是你的FastAPI视频流端点对Range请求的处理不符合Chrome的严格规范,导致Chrome拒绝加载。下面是具体修复步骤和代码:

1. 关键问题点

  • Chrome加载视频时可能先发送不带Range的请求获取元数据,当前代码直接返回400错误
  • 当Range的end值为空时,计算逻辑未限制在文件大小范围内,导致Content-Range响应无效
  • 缺少Content-Length响应头,Chrome无法识别返回的分片数据大小

2. 修改后的FastAPI端点代码

from fastapi import HTTPException, Header, Response
from pathlib import Path
import logging

logger = logging.getLogger(__name__)
CHUNK_SIZE = 1024 * 1024  # 1MB分片大小

@router.get("/video/{file}", tags=["video"])
async def get_video_stream(file: str, range: str = Header(None)):
    video_path = Path(f"/app/videos/{file}")
    
    # 先校验文件是否存在
    if not video_path.exists():
        logger.error(f"File not found: {video_path}")
        raise HTTPException(status_code=404, detail="Video not found")
    
    filesize = video_path.stat().st_size
    
    # 处理不带Range的请求(Chrome可能先发该请求获取元数据)
    if range is None:
        return Response(
            video_path.read_bytes(),
            status_code=200,
            media_type="video/mp4",
            headers={
                "Content-Length": str(filesize),
                "Accept-Ranges": "bytes"
            }
        )
    
    # 解析Range头,处理异常格式
    try:
        start_str, end_str = range.replace("bytes=", "").split("-")
        start = int(start_str) if start_str else 0
        # 空end值设为文件最后一个字节的索引(字节范围是左闭右闭)
        end = int(end_str) if end_str else filesize - 1
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid Range header")
    
    # 确保start和end在合法范围内
    start = max(0, min(start, filesize - 1))
    end = max(start, min(end, filesize - 1))
    
    chunk_size = end - start + 1
    
    # 读取分片数据
    with open(video_path, "rb") as video:
        video.seek(start)
        data = video.read(chunk_size)
    
    headers = {
        "Content-Range": f"bytes {start}-{end}/{filesize}",
        "Accept-Ranges": "bytes",
        "Content-Length": str(chunk_size),  # 必须添加,Chrome依赖该头
    }
    
    return Response(
        data,
        status_code=206,
        headers=headers,
        media_type="video/mp4"
    )

3. 前端视频标签优化(可选)

添加controls方便测试,playsinline适配移动端播放:

<video
  muted
  preload="metadata"
  controls
  playsinline
>
  <source
    src={`http://localhost:8005/video/test.mp4`}
    type="video/mp4"
  />
</video>

为什么Firefox能正常工作?

Firefox对HTTP Range响应的容错性更高,即使缺少Content-Length或end值超出范围,仍会尝试加载视频;而Chrome严格遵循HTTP规范,必须满足所有响应要求才能处理流式视频。

内容的提问来源于stack exchange,提问作者Soubriquet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 16:15:32