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

将Base64视频存入MongoDB后UI渲染报错:无支持格式视频

解决视频存储MongoDB后UI渲染「无支持格式视频」的问题

问题根源分析

你目前的代码存在两个关键问题:

  1. 虽然转换了视频为Base64,但存入数据库时并没有使用转好的encodedData,而是直接存储了fs.readFileSync返回的Buffer对象;
  2. 前端渲染时没有构建正确的Data URI格式,导致浏览器无法识别视频资源。

修正步骤

1. 修正数据库存储代码

确保存储的是Base64字符串,同时修复Promise错误处理逻辑(create方法已自动完成保存,无需额外调用save):

const path = "video file path";  
// 转换视频为Base64字符串
const encodedData = fs.readFileSync(path).toString("base64");

const obj = {    
  name: req.body.name,     
  desc: req.body.desc,     
  img: { 
    data: encodedData,  // 使用转好的Base64字符串
    contentType: "video/mp4",     
  },  
};   

imgSchema.create(obj)
  .then(() => res.redirect("/"))
  .catch(err => console.log(err));

2. 后端获取并传递数据

从MongoDB取出数据后,直接将Base64字符串和内容类型返回给前端:

// 示例查询接口
app.get('/videos/:id', async (req, res) => {
  const video = await imgSchema.findById(req.params.id);
  res.json({
    name: video.name,
    desc: video.desc,
    base64Data: video.img.data,
    contentType: video.img.contentType
  });
});

3. 前端正确渲染视频

构建符合标准的Data URI作为视频源,让浏览器能识别资源:

<video controls width="600">
  <source id="videoSource" type="video/mp4">
</video>

<script>
// 假设从后端接口获取到视频数据
const videoData = {
  base64Data: "你的Base64字符串",
  contentType: "video/mp4"
};

const sourceElement = document.getElementById('videoSource');
sourceElement.src = `data:${videoData.contentType};base64,${videoData.base64Data}`;
</script>

额外检查项

  • 确认本地视频本身是有效的MP4格式:直接在浏览器中打开本地视频文件,验证是否能正常播放;
  • 如果坚持存储Buffer而非Base64,后端取出时需先转换为Base64:video.img.data.toString('base64')。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 12:30:15