简体   繁体   English

如何从react js中的url下载文件(.jpg/.txt/.pdf/.mp4)?

[英]How to download a file(.jpg/.txt/.pdf/.mp4) from url in react js?

I am trying to download file from absolute url in react js.我正在尝试从 react js 中的绝对 url 下载文件。

Any help or suggestions are appreciated.任何帮助或建议表示赞赏。

只需使用download属性就可以这样做。

<a href="path to file" download> Download </a>

If you're using React Router, use the below given code.如果您使用的是 React Router,请使用下面给出的代码。

<Link to="/document/mydocument.pdf" target="_blank" download>Download</Link>

Where /document/mydocument.pdf is inside your public folder. /document/mydocument.pdf在您的公共文件夹中。

It would be best if you could create an endpoint which will give you the file with the correct headers.如果您可以创建一个端点,它将为您提供具有正确标题的文件,那将是最好的。 When you create the endpoint, look for Content-Disposition and Content-Type.创建端点时,查找 Content-Disposition 和 Content-Type。 This will trigger an automatic and consistent download through-out all browsers.这将在所有浏览器中触发自动且一致的下载。

The problem is that front-end code regarding download and the download attribute can behave differently depending on the browser.问题是关于下载和下载属性的前端代码的行为可能因浏览器而异。 If you are not able to serve them through an endpoint, I think you will always need to keep the trade-offs in mind like inconsistent behavior through different browsers.如果您无法通过端点为它们提供服务,我认为您将始终需要牢记权衡,例如通过不同浏览器的不一致行为。

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

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