下载视频流

60 阅读1分钟
/**
 * 下载视频文件
 * @param videoUrl - 视频文件的URL地址
 * @param cameraName - 摄像头名称,用于生成下载文件名
 * @returns 无返回值的异步函数
 */
export async function downloadVideo(videoUrl, cameraName) {
  try {
    // 创建一个临时的a标签来触发下载
    const link = document.createElement('a');
    link.href = videoUrl;
    // 设置下载文件名,可以根据需要自定义
    link.download = `${cameraName || 'video'}_${new Date().getTime()}.mp4`;
    link.style.display = 'none';
    
    // 添加到页面并触发点击
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
  } catch (error) {
    console.error('下载失败:', error);
    // 如果直接下载失败,可以考虑使用fetch获取后再下载
    try {
      const response = await fetch(videoUrl);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      
      const link = document.createElement('a');
      link.href = url;
      link.download = `${cameraName || 'video'}_${new Date().getTime()}.mp4`;
      link.style.display = 'none';
      
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (fetchError) {
      console.error('通过fetch下载也失败:', fetchError);
      // 最后回退到原始方法
      window.open(videoUrl);
    }
  }
}