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

Как скачать один файл с github

  • автор:

Скачивание архивов исходного кода

Вы можете скачать моментальный снимок кода в репозитории.

Overview of source code archives

You can download a snapshot of any branch, tag, or specific commit from GitHub.com. These snapshots are generated by the git archive command in one of two formats: tarball or zipball. Snapshots don’t contain the entire repository history. If you want the entire history, you can clone the repository. For more information, see «Cloning a repository.»

Downloading source code archives

You can download the source code archives in three ways.

Downloading source code archives from the repository view

On GitHub.com, navigate to the main page of the repository.

Above the list of files, click

Code.

Download ZIP.

Downloading source code archives from a release

On GitHub.com, navigate to the main page of the repository.

To the right of the list of files, click Releases.

Screenshot of the main page of a repository. A link, labeled "Releases", is highlighted with an orange outline.

Scroll down to the «Assets» section of the release.

To download the source code, click

Source code (zip) or

Source code (tar.gz).

Downloading source code archives from a tag

On GitHub.com, navigate to the main page of the repository.

To the right of the list of files, click Releases.

Screenshot of the main page of a repository. A link, labeled "Releases", is highlighted with an orange outline.

At the top of the Releases page, click Tags.

To download the source code, click

zip or

tar.gz.

Screenshot of the "Tags" page of a repository. The zip and tar.gz options are outlined in dark orange.

Source code archive URLs

Source code archives are available at specific URLs for each repository. For example, consider the repository github/codeql . There are different URLs for downloading a branch, a tag, or a specific commit ID.

Type of archive Example URL
Branch main https://github.com/github/codeql/archive/refs/heads/main.tar.gz
Tag codeql-cli/v2.12.0 https://github.com/github/codeql/archive/refs/tags/codeql-cli/v2.12.0.zip
Commit aef66c4 https://github.com/github/codeql/archive/aef66c462abe817e33aad91d97aa782a1e2ad2c7.zip

Note: You can use either .zip or .tar.gz in the URLs above to request a zipball or tarball respectively.

Stability of source code archives

Source code archives are generated on request, cached for a while, and then deleted. If the same archive is requested again in the future, it’ll be regenerated. It’s important to understand what guarantees GitHub makes about source code archives.

  • An archive of a commit ID will always have the same file contents whenever it’s requested, assuming the commit ID is still in the repository and the repository’s name has not changed.
  • Because branches and tags can move to different commit IDs, future downloads of an archive may have different contents than previously downloaded archives of the same branch or tag. Assuming the branch or tag still points at the same commit ID, it will have the same file contents.
  • The exact compression settings used to generate a zipball or tarball may change over time. The extracted contents won’t change if the branch or tag doesn’t change, but the outer compressed archive may have a different byte layout. GitHub will give at least six months’ notice before changing compression settings.
  • The name of the repository is part of the directory structure inside the archive. Therefore, if the repository name changes, the root directory name will change as well.

If you rely on stability of source code archives for reproducibility (ensuring you always get identical files inside the archive), we recommend using the archives REST API with a commit ID for :ref . Using the commit ID ensures you’ll always get the same file contents inside the archive and you’ll be immune to repositories rewriting tags or moving branch heads.

If you rely on stability of archives for security (for example: to ensure you don’t attempt to unzip a maliciously-crafted file), we recommend using releases instead of using source downloads. For more information, see «About releases.»

You can use something like this third-party GitHub action to create and push these files as part of your release process. The Release Assets REST API can later be used to retrieve them.

How do I download a particular file from GitHub?

I only need one particular file from a project published on GitHub so it makes little sense to download the whole project. But I just can’t find the download button.

5 Answers 5

If you’re viewing the contents of the file itself there should be a «Raw» button.

get raw

  • Right-click on that and select the «Save content as. » (or similar depending on your browser)
  • Click through to see the contents dumped onto the screen and save from there

In the list of files, every filename is a link. A simple right-click and «Save link as. » (or equivalent for your browser) will allow you to download a single file.

This breaks down with HTML files, however. You’ll need to use the «Raw» button on the file page as Eight Days of Malaise’s answer describes. I’m using Google Chrome. You may have a different experience on a different browser.

Check out RawGit which is a free service to serve files directly from Github with proper Content-type headers.

If you are using the Chromium browser, just hold down the ALT key and left click on the file to download it.

(Doesn’t work with Mozilla Firefox, haven’t tested other browsers.)

theLittleEndian's user avatar

You can try github-files-fetcher, it is a command line tool which downloads a single folder or file from a GitHub repo.

Think a real scenario: you were visiting the following webpage page and wanna download the async subdirectory alone.

How to Download From GitHub: A Beginner’s Guide

Jamie Juviler

GitHub is one of the largest developer resources, and an absolute must-know for aspiring web developers to explore and share projects online.

person using a computer do download from github

If you’re just starting out with git and GitHub, taking open-source code from GitHub to experiment with or add to your own projects is one great way to learn or develop your own apps. You can even connect your GitHub repository to your preferred hosting to deploy and test your apps. To do that, you’ll need to learn the basics: getting a file from GitHub onto your computer.

Download Now: 50 Code Templates [Free Snippets]

50 Free Coding Templates

Free code snippet templates for HTML, CSS, and JavaScript — Plus access to GitHub.

  • Navigation Menus & Breadcrumbs Templates
  • Button Transition Templates
  • CSS Effects Templates
  • And more!

You’re all set!

Click this link to access this resource at any time.

How to Download a GitHub Repository

GitHub is made up of repositories. A repository is a place where all files in a project can be stored, accessed, tracked, and modified. To download a repository, follow these steps:

1. Navigate to the GitHub repository page. If it’s a public repository, you can visit the page without logging in. If it’s a private repository, you’ll need to log in and have the proper permissions to access it.

2. On the main repository page, click the green Code button.

the main github page with the code button circled

3. In the menu that appears, click Download ZIP. The entire repository will be downloaded to your device as a zipped file.

the github download zip button

With that, you should be able to open the file locally.

How to Download a Release From GitHub

Repositories may also put out releases, which are packaged versions of the project. To download a release:

1. Navigate to the GitHub repository page. If it’s a public repository, you can visit the page without logging in. If it’s a private repository, you’ll need to log in and have the proper permissions to access it.

2. Click Releases, located on the right-side panel.

the releases option int he github side panel

3. You’ll be brought to a page listing releases from newest to oldest. Under the release that you want to download, locate the Assets section. Click a file under this section to download it.

assets in the github releases menu

You’ll be able to open this zipped file on your local device.

How to Download Multiple Files From GitHub

Unless you want to download an entire repository or release, there’s currently no way to bulk-download multiple files from GitHub. Depending on how many files you need from a repository, it may be best to download each individual file you need, or download the entire repository/release and delete the files you don’t need.

Get files from GitHub.

There’s a lot to learn when it comes to using GitHub — the platform packs a ton of features, and it can seem intimidating to newcomers. However, GitHub does an excellent job of making its tools simple and accessible. Case in point: downloading a single file or an entire repository is possible with just a few clicks.

New Call-to-action

Dozens of free coding templates you can start using right now.

DOWNLOAD FOR FREE DOWNLOAD FOR FREE

100% Free CRM

Nurture and grow your business with customer relationship management software.

Инструкция: как скачать файл с GitHub

Закройте IDE. Забудьте про пуши. Отрекитесь от коммитов и репозиториев.

Кадр: сериал «Остановись и гори»

Максим Сафронов

Если вы откроете файл в веб-версии GitHub, то заметите, что там нет отдельной кнопки «Скачать». Действительно, удобного способа загружать код напрямую с сайта разработчики не завезли, но есть альтернативные способы — в этой статье как раз о них поговорим. Заодно разберёмся, как скачивать файлы с GitHub на смартфон — пока только на Android-устройства, с айфонами всё сложно.

Способ первый

Скачать проект целиком

Все проекты на GitHub хранятся в репозиториях. Репозиторий — это место, где лежат файлы, библиотеки и фрагменты кода программы. Хорошая новость: если у вас есть доступ к проекту, его можно утащить себе на компьютер и разобрать на отдельные файлы. Вот как это сделать:

Шаг 1. Выберите проект, который хотите скачать. Ваши репозитории хранятся в разделе Your repositories, а проекты из свободного доступа можно найти с помощью окошка Search or jump to.

Шаг 2. Откройте выбранный проект. Мы, например, решили забрать себе классический «виндовый» калькулятор, с недавних пор выложенный в открытый доступ в аккаунте Microsoft.

Шаг 3. Нажмите кнопку Code в правом верхнем углу. Выпадет меню, в котором нужно выбрать Download ZIP.

Готово! Теперь у нас на компьютере есть собственная версия проекта. Можно запустить его в Visual Studio, а также в другом редакторе кода или IDE и допилить под свои нужды. Например, перекрасить кнопки в фиолетовый цвет — а почему бы и нет? ��

Способ второй

Скачать файл с GitHub через Raw

Единственный штатный способ скачать отдельный файл в GitHub — это кнопка Raw. Она превращает код файла в обычный текстовый документ без всякой разметки — в таком виде его можно легко загрузить на жёсткий диск. Не слишком удобный, но рабочий способ — давайте его тоже разберём.

Шаг 1. В репозитории проекта откройте файл, который хотите скачать.

Шаг 2. Когда файл откроется, нажмите кнопку Raw.

Шаг 3. Перед вами — исходный код файла, открытый в браузере. Чтобы его скачать, нажмите правой кнопкой мыши, а потом выберите «Сохранить как…».

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

Способ третий

Использовать расширение

В интернет-магазинах браузеров полно расширений, которые облегчают загрузку с GitHub. Например, GitZip for GitHub помогает скачивать не только файлы, но и целые папки. Рассказываем, как им пользоваться:

Шаг 1. Скачайте и установите утилиту в магазине расширений вашего браузера — есть версии для Chrome, Microsoft Edge и Mozilla.

На заметку: если расширение доступно для Chrome, то запустить его можно в любом браузере, работающем на хромовском движке Blink, — например, в Opera, Vivaldi или «Яндекс.Браузере».

Шаг 2. В репозитории проекта напротив каждого файла появятся чекбоксы — отметьте галочками те, которые хотите скачать.

Шаг 3. Нажмите на кнопку загрузки в правом нижнем углу.

Готово! Можно наслаждаться новыми возможностями до боли знакомого сервиса.

Бонус: как скачивать файлы из GitHub на Android-устройствах

По умолчанию в мобильной версии GitHub нет функции скачивания файлов. Но её можно активировать, если открыть в мобильном браузере версию сайта для ПК. После этого можно будет скачать отдельный файл либо весь проект в виде ZIP-архива.

Если нужен проект целиком:

Шаг 1. Откройте веб-страницу нужного репозитория через Google Chrome.

Шаг 2. В контекстном меню браузера нажмите на кнопку «Версия для ПК».

Шаг 3. После этого страница перезагрузится и откроется обычная десктопная версия сайта. Нажмите зелёную кнопку Code, а потом — Download ZIP.

Если нужен отдельный файл:

Шаг 1. Откройте на GitHub страницу файла и активируйте версию для ПК.

Шаг 2. Когда откроется десктопная версия страницы, нажмите кнопку Raw в правом верхнем углу.

Шаг 3. Снова вызовите контекстное меню браузера и нажмите на значок загрузки в самом верху — после этого на смартфон скачается нужный файл в формате .txt.

К сожалению, на iOS десктопная версия GitHub не открывается ни в одном браузере, поэтому функции Raw и Download ZIP недоступны. Если у вас есть рабочий способ — напишите нам в редакцию, добавим его в статью.

Что дальше

В этой статье мы обсудили нюансы работы только с веб-версией GitHub. Если хотите полностью перенести проект на свой компьютер и работать с ним локально, почитайте нашу статью про GitHub Desktop. Вы узнаете, как создать репозиторий, синхронизировать его с ПК и обновлять файлы удалённо.

Ещё можно почитать материал про систему контроля версий Git. Объясняем на понятных схемах, как работает технология, которая лежит в основе GitHub и других похожих сервисов. Вы поймёте, как там всё устроено, и сможете блеснуть знаниями на собеседовании.

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

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