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

如何从Blob URL下载指定文件名的PDF文件

指定PDF保存文件名的实现方法

你当前用window.open()打开Blob URL的方式,浏览器会默认用URL的随机后缀作为保存文件名,要指定文件名可以用以下两种方案:

方案一:直接触发指定文件名的下载(无需先预览)

创建一个隐藏的<a>标签,利用其download属性指定文件名,触发点击后即可下载带有指定名称的PDF:

const b64toBlob = (b64Data, extension) => {
  const byteCharacters = atob(b64Data);
  const len = byteCharacters.length;
  const buffer = new Uint8Array(len);
  for (let i = 0; i < len; i += 1) {
    buffer[i] = byteCharacters.charCodeAt(i);
  }
  return new Blob([buffer], { type: `application/${extension}` });
};

const blob = b64toBlob(base64Content, extension);
const url = URL.createObjectURL(blob);

// 创建a标签指定下载文件名
const a = document.createElement('a');
a.href = url;
a.download = '我的指定文件名.pdf'; // 替换为你需要的文件名
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

// 释放URL对象,避免内存泄漏
URL.revokeObjectURL(url);

方案二:先预览PDF,再提供指定文件名的下载按钮

如果需要先在新窗口预览PDF,再让用户下载指定文件名的文件,可以在预览窗口中插入下载按钮:

const b64toBlob = (b64Data, extension) => {
  const byteCharacters = atob(b64Data);
  const len = byteCharacters.length;
  const buffer = new Uint8Array(len);
  for (let i = 0; i < len; i += 1) {
    buffer[i] = byteCharacters.charCodeAt(i);
  }
  return new Blob([buffer], { type: `application/${extension}` });
};

const blob = b64toBlob(base64Content, extension);
const url = URL.createObjectURL(blob);

// 打开预览窗口
const previewWindow = window.open(url, '_blank');

// 窗口加载完成后插入下载按钮
previewWindow.onload = () => {
  const downloadBtn = document.createElement('button');
  downloadBtn.textContent = '下载PDF';
  downloadBtn.style.position = 'fixed';
  downloadBtn.style.top = '10px';
  downloadBtn.style.right = '10px';
  downloadBtn.style.zIndex = 9999;
  
  downloadBtn.onclick = () => {
    const a = document.createElement('a');
    a.href = url;
    a.download = '我的指定文件名.pdf'; // 指定文件名
    a.click();
  };
  
  previewWindow.document.body.appendChild(downloadBtn);
};

// 预览窗口关闭时释放URL资源
previewWindow.onbeforeunload = () => {
  URL.revokeObjectURL(url);
};

注意:download属性在同源场景下(本地Blob URL属于同源)完全有效,跨域场景可能受限。使用Blob URL后务必调用URL.revokeObjectURL()释放资源,避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:45:58