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

FastAPI返回视频至Axios后React无法展示的问题求助

视频上传后无法展示的问题修复方案

核心问题原因

Axios默认会将响应数据解析为JSON格式,导致后端返回的二进制视频数据被错误解析,生成的Blob对象无效,最终无法播放。

前端代码修复

需要在Axios请求中添加responseType: 'blob'配置,确保响应以Blob形式接收,无需手动重新创建Blob:

修改后的前端提交代码:

const handleVideoSubmit = async () => {
    try {
        updateLoading(true);
        if (sendVideo) {
            const formData = new FormData();
            formData.append('video', sendVideo);
            const response = await axios.post('url/videoProcess', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                responseType: 'blob' // 关键配置:指定响应类型为Blob
            });
            // 此时response.data已经是Blob对象,直接生成URL即可
            const videoUrl = URL.createObjectURL(response.data);
            updateLoading(false);
            toast('Video Başarılı Bir Şekilde İşlendi.');
            setProcessedVideo(videoUrl);
        }
    } catch (error) {
        console.error('Error submitting video:', error);
        toast(error.message);
        updateLoading(false);
    }
};

后端额外检查点

  • 确认temp/final_video.mp4文件确实存在且路径正确,避免因文件未生成或路径错误导致返回无效数据。
  • 确保后端拥有temp目录的读写权限,避免处理过程中无法写入或读取文件。
  • 可添加日志排查处理流程:
import logging
import os

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.post('/videoProcess')
async def process_video(video: UploadFile=File(...)):
    video_file=await video.read()
    with open('temp/video_data.mp4','wb+')as f:
        f.write(video_file)
    # video processing here
    logger.info("视频处理完成,准备返回文件")
    # 检查处理后的文件是否存在
    if not os.path.exists('temp/final_video.mp4'):
        logger.error("处理后的视频文件不存在")
        return {"error": "Processed video not found"}
    response = FileResponse('temp/final_video.mp4', media_type='video/mp4')
    return response

内容的提问来源于stack exchange,提问作者İlker Galip ATAK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:01:26