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

React应用中基于Base64字符串实现文件下载按钮的方案咨询

React中Base64格式PDF文件的下载实现方案

完整代码实现

import { Button } from 'react-bootstrap';

function DownloadButton() {
  function filedownload() {
    // 替换为实际的文件名(需带.pdf后缀)和Base64内容
    const filename = 'target.pdf';
    const b64string = '你的Base64格式PDF内容';

    // 移除Base64前缀(如果存在)
    const cleanBase64 = b64string.replace(/^data:application\/pdf;base64,/, '');
    // 解码Base64为二进制数组
    const byteChars = atob(cleanBase64);
    const byteNumbers = Array.from(byteChars, char => char.charCodeAt(0));
    const byteArray = new Uint8Array(byteNumbers);
    // 创建PDF Blob对象
    const pdfBlob = new Blob([byteArray], { type: 'application/pdf' });
    // 生成临时下载URL
    const downloadUrl = URL.createObjectURL(pdfBlob);
    // 创建并触发隐藏的a标签
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    // 清理临时资源
    setTimeout(() => {
      document.body.removeChild(link);
      URL.revokeObjectURL(downloadUrl);
    }, 100);
  }

  return (
    <Button onClick={filedownload} variant="primary">
      Download PDF
    </Button>
  );
}

export default DownloadButton;

关键细节说明

  • Base64前缀处理:如果你的Base64字符串包含data:application/pdf;base64,前缀,必须通过正则移除,否则解码会失败。
  • MIME类型指定:创建Blob时必须设置type: 'application/pdf',确保浏览器正确识别文件类型并触发对应下载行为。
  • 资源清理:下载完成后需销毁临时URL和动态创建的a标签,避免内存泄漏。
  • 按钮优化:直接将filedownload函数传递给onClick,无需额外包裹箭头函数(除非需要传递参数)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:10:05