【问题标题】:Download file in ReactJS app preserving the original filename在 ReactJS 应用程序中下载文件,保留原始文件名
【发布时间】:2021-02-07 11:43:11
【问题描述】:

我正在使用 nodejs/koa2 提供 pdf 文件

      ctx.body = readableStream;
      ctx.attachment('file.pdf');

文件成功到达并在客户端我使用 ReactJS 应用程序接收它:

  const document = useSelector(selectors.getFile(documentFile.key));
  if (document) {
    window.open(window.URL.createObjectURL(new Blob([document], { type: "application/octet-stream" })), "_self");
  }
...
  const openFile = useCallback((key) => {
    dispatch(actions.getFile.request(key))
  }, [dispatch]);

它成功下载了文件,但完全忽略了响应头Content-Disposition: attachment; filename="file.pdf",并以d3aa7870-bd35-4645-a926-294392343cfc 之类的名称下载它,该名称取自BLOB url:Request URL: blob:http://localhost:3000/d3aa7870-bd35-4645-a926-294392343cfc

能否请您告知如何在客户端以file.pdf 的名义正确保存它?

【问题讨论】:

    标签: reactjs blob


    【解决方案1】:

    只需创建一个元素并使用文件名设置下载属性

      const document = useSelector(selectors.getFile(documentFile.key));
      if (document) {
        const url =window.URL.createObjectURL(new Blob([document], { type: "application/octet-stream" }))
        const a = document.createElement("a");
        a.style = "display: none";
        document.body.appendChild(a);
        a.href = url;
        a.download = "fileName";
        a.click();
        window.URL.revokeObjectURL(url);
      }
    

    【讨论】:

      猜你喜欢
      • 2015-06-09
      • 1970-01-01
      • 2022-01-26
      • 2018-07-26
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      相关资源
      最近更新 更多