download

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:

This will allow you to change the name of the file actually being downloaded.

i used same code for download PFD file and i tested in all browser all are support but in safari this code is not working safari instead of download pdf file open in new tab.

caniuse.com/#search=download%20attribute Works in Chrome, Edge, Firefox, Opera and latest Android 4.4+ browsers, and not in Internet Explorer and Safari.

This is not working for me, I have a .exe file that I want users to download. However, tried to do this myself, to verify, but this ain’t working. It will just bring me to the source code, which I don’t want viewed.

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.)

why not use the download attribute, if you get a file like a jpg, it will download, instead of just opening.

@Dudeson please specify what «won’t work» and which version(s) of IE you are talking about. (It is now safe to use the approach described TIIUNDER’s much more recent answer below, though. It should get the accept mark.)

Читайте также:  Mr. Camel

@Sergiu the answer is seven years old. I can’t delete it, and the asker hasn’t responded to my request to switch the accept mark. nothing we can do, although I’ll add a link to the more current answer

In addition (or in replacement) to the HTML5’s the browser’s download to disk behavior can also be triggered by the following http response header:

Content-Disposition: attachment; filename=ProposedFileName.txt; 

This was the way to do before HTML5 (and still works with browsers supporting HTML5).

Is this the full answer? You also need to send a Content Type header and read the file to force the download. May want to and that to your answer. Full answer here: stackoverflow.com/a/1465631/2757916.

this is perfect for server side implementation, just precise also the content type. it is well supported compared to the download attribute

It may be possible to force by proxying the request to a service worker who can add this header but I’m not sure.

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:

AddType application/octet-stream EXTENSION 

Thanks! this is much simpler and is server-wide! 😀 I found this link that elaborates a little bit more. Thank you. htaccess-guide.com/adding-mime-types

That will make all files of that type download only. Fine if that’s what you want, but could cause fits if you forget and want another file of that type to display in-browser instead of download.

This thread is probably ancient by now, but this works in html5 for my local file.

Читайте также:  Задания для питон программиста

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.

Источник

Атрибут download

При наличии атрибута download браузер не переходит по ссылке, а предложит скачать документ, указанный в адресе ссылки.

Синтаксис

Обязательный атрибут

Значения

Значение по умолчанию

По умолчанию этот атрибут выключен.

      

Открыть файл в браузере

Скачать файл

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

HTML тег

HTML тег определяет отношение между текущим html-документом и внешним ресурсом, на который он ссылается. Он является пустым элементом (не имеет содержимого и закрывающего тега) и всегда должен располагаться внутри элемента . Чаще всего тег используется для подключения внешних таблиц стилей:

Первый атрибут href определяет адрес документа, который может быть как абсолютным так и относительным. Второй атрибут rel указывает связь между HTML файлом и тем, на что вы ссылаетесь, в данном случае мы ссылаемся на таблицу стилей, поэтому используется значение stylesheet. Атрибут type сообщает браузеру MIME тип документа, для таблиц стилей значением всегда будет «text/css» .

Примечание: по стандарту HTML5, при подключении к документу внешнего файла CSS, атрибут type указывать не требуется:

Предварительная загрузка страниц

Обычно, когда вы кликаете по ссылке на другую страницу приходится ждать несколько секунд пока она загрузится. Однако, вы можете настроить вашу веб-страницу таким образом, чтобы определённые страницы загружались заранее в кэш браузера в то время пока вы находитесь на текущей странице. Это означает, что когда вы кликнете по ссылке для перехода на другую веб-страницу, то она откроется сразу и не надо будет ждать, пока она загрузится. Это называется «предварительное получение страницы». Чтобы сделать это, используется тег с атрибутом rel=»prefetch» , а также указывается целевая страница, которая будет заранее загружена на компьютер.

Такая запись позволит заранее закешировать страницу tag_p.php на компьютере, пока вы читаете содержимое текущей страницы. Вы можете использовать тег для предварительной загрузки любого количества страниц вашего собственного сайта или любых других из интернета.

Примечание: вместо адреса на HTML-документ можно указать путь к файлу другого типа (картинку, видео и тд.).

Атрибуты

  • alternate — ссылка на альтернативную версию документа (то есть страницы для печати, перевод или зеркало).
  • author — определяет ссылку страницу об авторе документа или на страницу с контактными данными автора.
  • canonical — позволяет пометить страницы с дублирующимся контентом, это значит что все страницы, имеющие одинаковое содержимое должны содержать тег с атрибутом rel=»canonical» .

Атрибут href , в этом случае, должен содержать ссылку на страницу с идентичным содержимым, которую поисковые системы должны считать основной:

Источник

Оцените статью