# 前端下载云盘文件并且重命名

  function downloadBlob(data, filename, mimeType) {
    // 如果 data 不是 Blob,先转换成 Blob
    const blob = data instanceof Blob
      ? data
      : new Blob([data], { type: mimeType || 'text/vtt' });

    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename || 'download';
    setDownloadLoading(false);
    // 触发下载
    document.body.appendChild(a);
    a.click();

    // 清理
    setTimeout(() => {
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }, 100);
  }


  const handleDownload = async () => {

    const vttRes = await fetchVttDetail(id);
    console.log(vttRes,"vttResvttRes")
    if (!vttRes.code === 200) {
      message.error(vttRes.msg);
      return;
    }
    const { originalCaptionsOss, captionsOss } = vttRes.data;
    const url = captionsOss || originalCaptionsOss;
    if (!videoDetail) {
      message.error('课程详情获取失败!');
      return;
    }
    setDownloadLoading(true);
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob'; // 设置响应类型为 blob

    xhr.onload = function () {
      if (xhr.status === 200) {
        // 获取响应数据(Blob对象)
        var blob = xhr.response;
        downloadBlob(blob, `${videoDetail.videoName}${videoDetail.id}字幕.vtt`); // 使用上面的 downloadBlob 方法
      } else {
        console.error('下载失败,状态码:', xhr.status);
      }
    };

    xhr.onerror = function () {
      console.error('请求失败');
      setDownloadLoading(false);

    };

    xhr.send();
  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
最后更新时间: 7/2/2025, 2:56:43 PM