简体   繁体   English

如何在html中创建一个url下载链接?

[英]How can I make a url a download link in html?

A client wants a url to be a download link. 客户希望url成为下载链接。

Use case is like so : 用例是这样的

user gets linked to example.com/download once there, it downloads a pdf file. 用户在此处链接到example.com/download ,它会下载pdf文件。

Can I do this without php ? 我可以不用PHP吗?

HTML5 introduced the download attribute . HTML5引入了download属性

Supporting user-agents will offer to download the file foo.png when clicking this link: 单击此链接时,支持用户代理将提供下载文件foo.png

<a href="foo.png" download>Save the image</a>

You can also specify a different default file name that should be used: 您还可以指定应使用的其他默认文件名:

<a href="foo.png" download="image.png>Save the image</a>

Read more at http://www.w3.org/TR/html5/links.html#downloading-resources . 更多信息, 请访问http://www.w3.org/TR/html5/links.html#downloading-resources

Note that this only works for links . 请注意,这仅适用于链接 When users enter the URL directly into their browsers, this will have no effect, of course. 当用户直接在他们的浏览器中输入URL时,这当然没有任何效果。 If you want that, you need to send specific HTTP headers. 如果需要,您需要发送特定的HTTP标头。 See for example the question: How to force download of a file? 例如,请参阅问题: 如何强制下载文件? . You don't necessarily need a programming language like PHP for that. 你不一定需要像PHP那样的编程语言。 You can do it with, for example, .htaccess , too: Force File(image) Download with .htaccess 例如,您也可以使用.htaccess执行此操作: 强制文件(图像)使用.htaccess下载

How a file is displayed is browser specific. 文件的显示方式是特定于浏览器的。 Some may force you to download while some directly render it on the browser. 有些人可能会强迫您下载,而有些人会直接在浏览器上呈现它。

If you want to force the browser to download the file then you can set in Header the 如果要强制浏览器下载文件,则可以在Header中设置

Content-Type : application/octet-stream

You only need a link (anchor tag). 您只需要一个链接(锚标记)。 The way the link behaves on click will depend on what browser you are and what settings you have in that particular browser. 链接在单击时的行为方式取决于您使用的浏览器以及该特定浏览器中的设置。 Some browsers will prompt you to open or save the file, other browsers will open the PDF file on a new tab or window. 某些浏览器会提示您打开或保存文件,其他浏览器会在新选项卡或窗口中打开PDF文件。

<a href="path/to/your/file.pdf">Download PDF</a>

You'll also need to make sure that the path to the PDF file is correct on the href property of your anchor tag. 您还需要确保在锚标记的href属性上PDF文件的路径是正确的。

使用此(HTML)而不是PHP:

<a href="http://example.com/download/asdf.pdf">Download pdf</a>

使用包含pdf文件的完整网址。

<a href="http://example.com/download/file.pdf" target="_blank">Download</a>

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

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