Как в html сделать скачивание файла
There are so many downloads from the websites daily, we can’t even count it’s beyond imagination. But as a programmer, you should know about creating a download link for yourself too so that when you need to add it to your website, it will be easy for you to add this feature. In this article, we will learn how to create a download link with html.
Download Link is a link that will download the specific file when the user clicks on it. Now, let’s talk about the attribute which will be used in the code while writing it. The “download” attribute is used to make the link downloadable. It will specify the target (pdf, zip, jpg, doc, etc) that will be downloaded only when the user clicks on the link.
Note: The download attribute can be only used when the href attribute is set before.
Syntax:
Example: This example describes how to create a downloadable link.
How can I create download link in HTML?
I have a basic idea of HTML. I want to create the download link in my sample website, but I don’t have idea of how to create it. How do I make a link to download a file rather than visit it?
![]()
12 Answers 12
In modern browsers that support HTML5, the following is possible:
You also can use this:
This will allow you to change the name of the file actually being downloaded.
![]()
This answer is outdated. We now have the download attribute. (see also this link to MDN)
If by «the download link» you mean a link to a file to download, use
the target=_blank will make a new browser window appear before the download starts. That window will usually be closed when the browser discovers that the resource is a file download.
Note that file types known to the browser (e.g. JPG or GIF images) will usually be opened within the browser.
You can try sending the right headers to force a download like outlined e.g. here. (server side scripting or access to the server settings is required for that.)
![]()
In addition (or in replacement) to the HTML5’s <a download attribute already mentioned,
the browser’s download to disk behavior can also be triggered by the following http response header:
This was the way to do before HTML5 (and still works with browsers supporting HTML5).
![]()
A download link would be a link to the resource you want to download. It is constructed in the same way that any other link would be:
![]()
To link to the file, do the same as any other page link:
To force things to download even if they have an embedded plugin (Windows + QuickTime = ugh), you can use this in your htaccess / apache2.conf:
This thread is probably ancient by now, but this works in html5 for my local file.
<p><a href=»file:///. example.pdf» download target=»_blank»>test pdf</a></p>
This should open the pdf in a new windows and allow you to download it (in firefox at least). For any other file, just make it the filename. For images and music, you’d want to store them in the same directory as your site though. So it’d be like
There’s one more subtlety that can help here.
I want to have links that both allow in-browser playing and display as well as one for purely downloading. The new download attribute is fine, but doesn’t work all the time because the browser’s compulsion to play the or display the file is still very strong.
BUT.. this is based on examining the extension on the URL’s filename!You don’t want to fiddle with the server’s extension mapping because you want to deliver the same file two different ways. So for the download, you can fool it by softlinking the file to a name that is opaque to this extension mapping, pointing to it, and then using download’s rename feature to fix the name.
I was hoping just throwing a dummy query on the end or otherwise obfuscating the extension would work, but sadly, it doesn’t.
HTML <a> download Attribute
Download file when clicking on the link (instead of navigating to the file):
More «Try it Yourself» examples below.
Definition and Usage
The download attribute specifies that the target (the file specified in the href attribute) will be downloaded when a user clicks on the hyperlink.
The optional value of the download attribute will be the new name of the file after it is downloaded. There are no restrictions on allowed values, and the browser will automatically detect the correct file extension and add it to the file (.img, .pdf, .txt, .html, etc.).
If the value is omitted, the original filename is used.
Browser Support
The numbers in the table specify the first browser version that fully supports the attribute.
Заметка: использование HTML5 атрибута "download"

Thoriq Firdaus Last updated Apr 27, 2015
Создать ссылку на скачивание в HTML довольно просто; Добавляете тег <a> и в атрибуте href указываете путь к файлу. Однако, некоторые типы файлов (например изображения, .pdf, .txt, и .doc) не будут скачиваться. Вместо этого они откроются в браузере.
Существуют решения, которые можно использовать, если у вас есть серверный доступ к сайту, например настройка .htaccess для скачивания этих файлов напрямую. Если ваш сайт размещен на бесплатных площадках, таких как WordPress.com, Blogspot или Github, которые не позволяют этого сделать — следует использовать атрибут download .
Использование атрибута «Download»
Атрибут download является частью спецификации HTML5 и определяет ссылку именно как ссылку на скачивание, а не навигационную.
Он также позволяет переименовать файл после скачивания. Файл, находящийся на сервере, особенно если он создается автоматически, может называться например так acme-doc-2.0.1.txt . Но для пользователей было бы лучше скачивать файл с более разумным именем, возможно таким: Acme Documentation (ver. 2.0.1).txt (не забываем расширение файла).
Вот как это будет выглядеть:
Попробуйте скачать файл с этой страницы, он должен скачаться с названием, которое указано в атрибуте download .


Несколько замечаний:
- Firefox разрешает загрузку файлов лишь с текущего источника (same origin), заботясь о безопасности. Файл должен приходить именно с вашего сервера или домена, в противном случае он будет открыт в браузере.
- Пока загрузка cross-origin файлов поддерживается в Chrome и последней версии Opera (с Chromium/Blink), эти браузеры проигнорируют значение атрибута. Другими словами, имя файла останется неизменным.
Обеспечиваем Fallback
На время написания этой статьи поддержки атрибута download еще не было в Safari и (как можно было ожидать) в Internet Explorer. Cогласно modern IE status, эта фича в настоящее время находится в верхней части списка разработки и получает много голосов.


Тем временем, мы можем добавить неплохой запасной вариант (fallback) для браузеров, которые не поддерживают этот атрибут — показывать дополнительные инструкции под ссылкой на скачивание. Чтобы это сделать, нам нужно скачать Modernizr с включенным тестом на поддержку атрибута download .

Конфигурация сборки Modernizr.
Затем мы можем добавить следующий скрипт.
Скрипт проверит, поддерживает ли браузер данный атрибут; если нет — то под всеми ссылками с указанным download атрибутом будет добавлен новый <div> с подсказкой.

Текстовая инструкция показывается в Safari.
Подводя итог
Атрибут download делает обработку ссылок на скачивание очень удобным для тех, кто не имеет доступа к серверным настройкам. С нетерпением жду, что Internet Explorer и Safari скоро реализуют поддержку атрибута download !