StarFire_xm
  • 文章
  • 粉丝
  • 评论

文件流/oss地址导出文件自定义命名

2025-08-19 10:46:450 次浏览0 次评论技能类型: js
1.通过接口请求返回blob文件流的方式导出文件自定义文件名
const export= async () => {
  exportLoading.value = true;
  try {
    // 调用导出接口,传递搜索条件
    const blobAxiosResponse:any = await downloadTemplate({ type: 1 });

    // 创建下载链接
    const link = document.createElement('a');
    const blobUrl = URL.createObjectURL(blobAxiosResponse);
    link.href = blobUrl;
    link.download = 'aaa.xlsx'; // 设置文件名
    document.body.appendChild(link);
    link.click();

    // 释放 URL 对象
    URL.revokeObjectURL(blobUrl);
    document.body.removeChild(link);
  } catch (error) {
    console.error('导出失败:', error);
    proxy?.$modal.msgError('导出失败');
  } finally {
    exportLoading.value = false; // 确保加载状态被重置
  }
};

2.通过oss地址下载文件重命名文件
async function downloadAll(urls, taskName) {
  for (let i = 0; i < urls.length; i++) {
    try {
      const url = urls[i];
      // 从URL中提取文件扩展名
      const fileExtension = url.split('.').pop() || 'xlsx';
      // 根据任务类型生成文件名
      const fileName = `${taskName}.${fileExtension}`;
      // 通过fetch获取文件blob
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`下载失败: ${response.status}`);
      }
      const blob = await response.blob();
      // 创建下载链接
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = fileName;
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      // 清理URL对象
      URL.revokeObjectURL(a.href);

      // 等待800ms再下载下一个
      await new Promise(resolve => setTimeout(resolve, 800));
     
    } catch (error) {
      console.error('下载文件失败:', error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      proxy?.$modal.msgError(`下载第${i + 1}个文件失败: ${errorMessage}`);
    }
  }
}


    发表

    还没有评论哦,来抢个沙发吧!