简体   繁体   English

如何从反应中调用 node.js API 来下载文件

[英]How to call a node.js API from react to download a file

Currently my API is connected to the Dataverse which responds with an Object with a file information, and the information I have in the API to send to the frontend is for example:目前我的 API 已连接到 Dataverse,该 Dataverse 以 Object 响应文件信息,而我在 API 中的信息发送到前端例如

{
  id:1;
  filename: example.pdf ;
  documentbody: (really long string);
  mimetype:'application/pdf'
}

And I want a user in React to be able to download this file if a button is clicked.如果单击按钮,我希望 React 中的用户能够下载此文件。 I have searched but haven't yet found a way to trigger the download in the backend neither in the frontend.我已经搜索过,但还没有找到在后端触发下载的方法,也没有在前端触发下载。

in Ur download function create an anchor tag programmatically set href and download stuff and then trigger the click event programmatically to start downloading.在 Ur 下载 function 以编程方式创建锚标记设置 href 并下载内容,然后以编程方式触发点击事件开始下载。

download(){
    const downloadLink = document.createElement('a');

    downloadLink.href = linkSource;
    downloadLink.download = filename;
    downloadLink.click();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM