how to download file in react js

前端 未结 12 1668
梦谈多话
梦谈多话 2020-12-01 05:49

I receive file url as response from api. when user clicks on download button, the file should be downloaded without opening file preview in a new tab. How to achieve this in

12条回答
  •  旧时难觅i
    2020-12-01 06:39

    browsers are smart enough to detect the link and downloading it directly when clicking on an anchor tag without using the download attribute.

    after getting your file link from the api, just use plain javascript by creating anchor tag and delete it after clicking on it dynamically immediately on the fly.

    const link = document.createElement('a');
    link.href = `your_link.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    

提交回复
热议问题