当前位置:首页 > React

react实现文件下载

2026-01-26 20:09:35React

使用 fetchaxios 下载文件

通过 fetchaxios 请求文件数据,将响应转换为 Blob 对象,并创建下载链接。以下是一个示例代码:

const downloadFile = async (url, filename) => {
  try {
    const response = await fetch(url);
    const blob = await response.blob();
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    console.error('Error downloading file:', error);
  }
};

使用 a 标签直接下载

对于不需要鉴权的文件,可以直接通过 a 标签的 download 属性实现下载:

react实现文件下载

const downloadFile = (url, filename) => {
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

处理后端返回的文件流

如果后端返回文件流(如 PDF、Excel 等),可以通过设置响应类型为 blob 并处理:

react实现文件下载

const downloadFile = async (url, filename) => {
  try {
    const response = await axios.get(url, { responseType: 'blob' });
    const blob = new Blob([response.data]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    console.error('Error downloading file:', error);
  }
};

处理大文件分片下载

对于大文件,可以分片下载并合并:

const downloadLargeFile = async (url, filename) => {
  try {
    const response = await fetch(url);
    const reader = response.body.getReader();
    const chunks = [];
    let receivedLength = 0;

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      chunks.push(value);
      receivedLength += value.length;
    }

    const blob = new Blob(chunks);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    console.error('Error downloading large file:', error);
  }
};

添加下载进度提示

通过监听 axiosfetch 的进度事件,显示下载进度:

const downloadFileWithProgress = (url, filename) => {
  axios({
    url,
    method: 'GET',
    responseType: 'blob',
    onDownloadProgress: (progressEvent) => {
      const percentCompleted = Math.round(
        (progressEvent.loaded * 100) / progressEvent.total
      );
      console.log(`Download progress: ${percentCompleted}%`);
    },
  }).then((response) => {
    const blob = new Blob([response.data]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  });
};

注意事项

  • 跨域问题:确保后端配置了 CORS 允许前端访问文件。
  • 文件名:后端可以通过响应头 Content-Disposition 指定文件名,前端可以从响应头中解析。
  • 错误处理:捕获并处理网络请求或文件操作中的错误。

标签: 文件react
分享给朋友:

相关文章

如何记忆react

如何记忆react

理解核心概念 React的核心概念包括组件、状态(state)、属性(props)、生命周期方法(类组件)和钩子(函数组件)。掌握这些基础概念是记忆React的关键。组件是React应用的构建块,分为…

如何下载react

如何下载react

下载 React 的方法 通过 npm 或 yarn 安装 React 可以通过包管理器 npm 或 yarn 安装。确保已安装 Node.js(包含 npm),然后在项目目录中运行以下命令:…

react如何验证

react如何验证

表单验证方法 在React中验证表单数据通常使用以下几种方式: 内置HTML5验证 利用HTML5原生表单验证属性如required、pattern等,结合form.noValidate属性禁用浏览…

react 如何运行

react 如何运行

运行 React 项目的步骤 安装 Node.js 确保系统已安装 Node.js(建议版本 16+),可通过官网下载并安装。安装后验证版本: node -v npm -v 创建 React 项目…

react如何安装

react如何安装

安装React的步骤 确保已安装Node.js(建议版本12或更高),可通过以下命令检查版本: node -v npm -v 使用Create React App快速搭建项目(推荐): npx c…

如何运行react

如何运行react

运行 React 项目的步骤 安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网 Node.js 下载并安装最新稳定版本。安装完成后,验证版本: node…