在ReactJS应用程序中下载文件,保留原始文件名

在ReactJS应用程序中下载文件,保留原始文件名,reactjs,blob,Reactjs,Blob,我正在使用nodejs/koa2提供pdf文件 ctx.body = readableStream; ctx.attachment('file.pdf'); 文件成功到达,在客户端,我使用ReactJS应用程序接收文件: const document = useSelector(selectors.getFile(documentFile.key)); if (document) { window.open(window.URL.createObject

我正在使用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]);
它成功下载文件,但完全忽略响应头
内容处置:附件;filename=“file.pdf”
并以类似于
d3aa7870-bd35-4645-a926-29439233CFC的名称下载它,该名称取自BLOB url:
请求url:BLOB:http://localhost:3000/d3aa7870-bd35-4645-a926-29439233CFC


请您建议如何在客户端以
file.pdf
的名称正确保存该文件?

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

const document=useSelector(selectors.getFile(documentFile.key));
如果(文件){
const url=window.url.createObjectURL(新Blob([document],{type:“application/octet stream”}))
常量a=document.createElement(“a”);
a、 style=“显示:无”;
文件.正文.附件(a);
a、 href=url;
a、 下载=“文件名”;
a、 单击();
window.URL.revokeObjectURL(URL);
}