Как добавить ссылку на скачивание файла html
Перейти к содержимому

Как добавить ссылку на скачивание файла html

  • автор:

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.

Как вставить ссылку в HTML и оформить ее в CSS?

Неотъемлемой и очень важной частью любого сайта являются ссылки, и несмотря на то, где ссылка расположена, и какие функции она выполняет ее необходимо оформить в соответствующем стиле.

В сегодняшней статье я хотела бы вам рассказать, как вставить ссылку в HTML, и показать, как можно ее оформить.

Навигация по статье:

Как вставить ссылку в HTML?

Итак, для создания простейшей ссылки нам необходимо воспользоваться атрибутом <a> и указать адрес, куда будет осуществляться переход при нажатии на ссылку.

Кроме атрибута href, который задает адрес перехода, тегу <a> можно задавать следующие атрибуты:

  • download – указывает на файл для скачивания.
  • name – якорь.
  • title — всплывающая подсказка при наведении.
  • accesskey — активация ссылки с помощью комбинации клавиш.
  • coords – задает координаты расположение активной области.
  • hreflang – определяет язык текста по ссылке.
  • rel — отношения между ссылаемым и текущим документами.
  • rev — отношения между текущим и ссылаемым документами.
  • shape — указывает форму области ссылки для изображений.
  • tabindex — последовательность переключения между ссылками при нажатии на клавишу Tab.
  • target — имя окна или фрейма, куда браузер будет загружать документ.
  • type — тип документа, на который осуществляется переход.

Большинство из данных атрибутов используются достаточно редко. Наиболее часто используемыми атрибутами являются href, download, target и name.

Как открыть ссылку в новой вкладке HTML?

Для открытия новой вкладке мы можем использовать атрибут target с атрибутом _blank.

<a>: The Anchor element

The <a> HTML element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.

Content within each <a> should indicate the link’s destination. If the href attribute is present, pressing the enter key while focused on the <a> element will activate it.

Try it

Attributes

This element’s attributes include the global attributes.

Causes the browser to treat the linked URL as a download. Can be used with or without a filename value:

  • Without a value, the browser will suggest a filename/extension, generated from various sources:
    • The Content-Disposition HTTP header
    • The final segment in the URL path
    • The media type (from the Content-Type header, the start of a data: URL, or Blob.type for a blob: URL)

    Note:

    • download only works for same-origin URLs, or the blob: and data: schemes.
    • How browsers treat downloads varies by browser, user settings, and other factors. The user may be prompted before a download starts, or the file may be saved automatically, or it may open automatically, either in an external application or in the browser itself.
    • If the Content-Disposition header has different information from the download attribute, resulting behavior may differ:
      • If the header specifies a filename , it takes priority over a filename specified in the download attribute.
      • If the header specifies a disposition of inline , Chrome and Firefox prioritize the attribute and treat it as a download. Old Firefox versions (before 82) prioritize the header and will display the content inline.

      The URL that the hyperlink points to. Links are not restricted to HTTP-based URLs — they can use any URL scheme supported by browsers:

      • Sections of a page with document fragments
      • Specific text portions with text fragments
      • Pieces of media files with media fragments
      • Telephone numbers with tel: URLs
      • Email addresses with mailto: URLs
      • While web browsers may not support other URL schemes, websites can with registerProtocolHandler()

      Hints at the human language of the linked URL. No built-in functionality. Allowed values are the same as the global lang attribute.

      A space-separated list of URLs. When the link is followed, the browser will send POST requests with the body PING to the URLs. Typically for tracking.

      How much of the referrer to send when following the link.

      • no-referrer : The Referer header will not be sent.
      • no-referrer-when-downgrade : The Referer header will not be sent to origins without TLS (HTTPS).
      • origin : The sent referrer will be limited to the origin of the referring page: its scheme, host, and port.
      • origin-when-cross-origin : The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
      • same-origin : A referrer will be sent for same origin, but cross-origin requests will contain no referrer information.
      • strict-origin : Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don’t send it to a less secure destination (HTTPS→HTTP).
      • strict-origin-when-cross-origin (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
      • unsafe-url : The referrer will include the origin and the path (but not the fragment, password, or username). This value is unsafe, because it leaks origins and paths from TLS-protected resources to insecure origins.

      The relationship of the linked URL as space-separated link types.

      Where to display the linked URL, as the name for a browsing context (a tab, window, or <iframe> ). The following keywords have special meanings for where to load the URL:

      • _self : the current browsing context. (Default)
      • _blank : usually a new tab, but users can configure browsers to open a new window instead.
      • _parent : the parent browsing context of the current one. If no parent, behaves as _self .
      • _top : the topmost browsing context (the «highest» context that’s an ancestor of the current one). If no ancestors, behaves as _self .

      Note: Setting target=»_blank» on <a> elements implicitly provides the same rel behavior as setting rel=»noopener» which does not set window.opener .

      Hints at the linked URL’s format with a MIME type. No built-in functionality.

      Deprecated attributes

      Hinted at the character encoding of the linked URL.

      Note: This attribute is deprecated and should not be used by authors. Use the HTTP Content-Type header on the linked URL.

      Used with the shape attribute. A comma-separated list of coordinates.

      Was required to define a possible target location in a page. In HTML 4.01, id and name could both be used on <a> , as long as they had identical values.

      Note: Use the global attribute id instead.

      Specified a reverse link; the opposite of the rel attribute. Deprecated for being very confusing.

      The shape of the hyperlink’s region in an image map.

      Note: Use the <area> element for image maps instead.

      Ссыл­ка для ска­чи­ва­ния

      Иногда передо мной стоит задача сделать ссылку, которая должна открывать системный диалог для сохранения файла. Браузеры достаточно умны, чтобы открывать такой диалог при скачивании бинарников вроде архивов или EXE-файлов. Но что делать, если я хочу скачивать картинки или какие-нибудь видео? Именно скачивать, не открывать для просмотра.

      Заголовок Content-Disposition Скопировать ссылку

      Самый правильный способ попросить браузер скачать файл — добавить на стороне сервера заголовок Content-Disposition к потоку с файлом.

      Когда браузер видит у заголовка значение attachment , то пытается скачать файл.

      Но иногда у вас просто нет возможности настроить сервер под свои нужды и добавить ещё один mod_rewrite . Нужен какой-то более браузерный способ решить задачу.

      Атрибут download Скопировать ссылку

      Самый простой способ — добавить атрибут download к ссылке.

      Если вы добавите его просто так, без значения, браузер постарается получить имя файла либо из заголовка Content-Disposition (опять он, и у него довольно высокий приоритет), либо из пути файла.

      Но вы можете задать значение атрибуту download , и тогда это значение станет именем скачиваемого файла. Это может быть полезно, если у ваших файлов какие-нибудь странные автогенерируемые урлы вроде https://cdn/images/a1H5-st42-Av1f-rUles .

      Важно! Вся эта магия атрибутов не для ссылок с других доменов (cross-origin). Вы не можете управлять чужими ресурсами из соображений безопасности.

      И помните, что IE и старые Safari не понимают атрибут download . Проверьте в Can I use….

      blob: и data: Скопировать ссылку

      Полезный лайфхак, чтобы помочь вашим пользователям сохранять картинки котиков в удобном для них формате. Если вы на своём сайте используете картинки в форматах AVIF или WebP, есть очень высокая вероятность, что ни один пользователь не сможет сохранить их к себе на компьютер или смартфон, чтобы потом пересмотреть. Точнее, сохранить-то смогут, а вот посмотреть вне браузера не смогут. Печаль.

      Чтобы помочь пользователям, используйте data: или blob: внутри атрибута href .

      Шаг 1. Нарисуйте картинку на Canvas Скопировать ссылку

      Шаг 2а. Сохранить картинку как блоб в атрибут href ссылки Скопировать ссылку

      Да-да, я могу сохранить AVIF как JPEG. Классно, правда? Пользователь скачал всего 4 КБ AVIF с сервера, а получил 13 КБ JPEG на клиенте!

      Шаг 2б. Сохранить картинку как data в атрибут href ссылки. Скопировать ссылку

      Некоторые браузеры не умеют работать с блобами, поэтому вы можете помочь им при помощи data-урлов.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *