Curl upload file windows

The short answer

To upload a file with curl using the HTTP POST method, you can use the -F flag (short for —form) with the following syntax:

$ curl -F "<form_field>=@<local_file_path>"<upload_url>

Where:

  • form_field is the name of the form field that will receive the file.
  • local_file_path is the path to the local file you want to upload.
  • upload_url is the URL where you want to send the file.

For example:

$ curl -F "[email protected]" https://example.com/upload

This command sends an HTTP POST request to https://example.com/upload with a form field named file containing the contents of the file mydocument.pdf, while setting the Content-Type header to multipart/form-data.

Note that this method is typically used for uploading files via HTTP or HTTPS, and not for FTP or SFTP transfers, which are covered below.

You can learn more about cURL with our other articles on how to send HTTP POST requests with cURL and how to set HTTP headers with cURL.

Easily retrieve this command using Warp’s AI Command Suggestions

If you’re using Warp as your terminal, you can easily retrieve this command using the Warp AI Command Suggestions feature:

Entering curl upload file in the AI Command Suggestions will prompt a curl command that can then quickly be inserted into your shell by doing CMD+ENTER.

Uploading a file with curl using HTTP PUT

To upload a file using the HTTP PUT method, you can use the curl command with the -T flag (short for —upload-file) as follows:

$ curl -T <local_file_path> <upload_url>

Where:

  • local_file_path is the path to the local file you want to upload.
  • upload_url is the URL where you want to send the file using the PUT method.

For example:

$ curl -T ./mydocument.txt https://example.com/upload

This command sends an HTTP PUT request to https://example.com/upload with the specified file as the message body of the request.

Uploading a file to an FTP server

To upload a file to an FTP server with curl, you can use the following syntax:

$ curl -T <local_file_path> -u <username>:<password>ftp://<ftp_server_url>/<remote_directory>/

Where:

  • local_file_path is the path to the local file you want to upload.
  • username is your FTP username.
  • password is your FTP password.
  • ftp_server_url is the URL of the FTP server you want to connect to.
  • remote_directory is the directory on the FTP server where you want to upload the file.

For example:

$ curl -T ./mydocument.txt -u myuser:mypassword ftp://ftp.example.com/uploads/

Note that you should ensure proper permissions and the existence of the remote directory on the FTP server before proceeding. If security is a concern, consider using secure FTP (SFTP) or other encryption methods, as plain FTP transfers data without encryption.

Uploading a file to an SFTP server

To upload a file to an SFTP server with curl, you can use this command syntax:

$ curl -T <local_file_path> sftp://<username>@<sftp_server_url>/<remote_directory>/

Where:

  • local_file_path is the path to the local file you want to upload.
  • username is your SFTP username.
  • sftp_server_url is the URL of the SFTP server you want to connect to.
  • remote_directory is the directory on the SFTP server where you want to upload the file.

For example:

$ curl -T ./mydocument.txt sftp://[email protected]/uploads/

Uploading a file to Artifactory

To upload a file to Artifactory with curl, you can use the following command syntax:

$ curl -u <username>:<password> -T "<local_file_path>" "<artifactory_url>/artifactory/<repository>/<target_path>/<filename>"

Where:

  • username is your Artifactory username.
  • password is your Artifactory password.
  • local_file_path is the path to the local file you want to upload.
  • artifactory_url is the URL of your Artifactory instance.
  • repository is the name of the repository where you want to store the file.
  • target_path is the optional directory path within the repository where you want to place the file.
  • filename is the name you want to give to the uploaded file.

For example:

$ curl -u myuser:mypassword -T myartifact.jar "https://artifactory.example.com/artifactory/myrepo/myfolder/myartifact.jar"

Uploading a file to an S3 bucket using a presigned URL

To upload a file to an Amazon S3 bucket with curl using a presigned URL, you can use the following command syntax:

$ curl --upload-file <local_file_path> <presigned_url>

Where:

  • local_file_path is the path to the local file you want to upload.
  • presigned_url is the presigned URL generated for your S3 bucket and object, which includes authentication and expiration information.

For example:

$ curl --upload-file ./mydocument.pdf "https://s3.amazonaws.com/mybucket/myobject?AWSAccessKeyId=YOUR_ACCESS_KEY&Expires=EXPIRATION_TIMESTAMP&Signature=SIGNATURE"

This command sends a PUT request to the presigned URL with the specified file as the request body.

Uploading a file on Windows

To upload a file on a Windows operating system with curl, you can use a command similar to the ones provided earlier, with adjustments for Windows file paths.

Here’s the general command structure:

$ curl -F "<form_field>=@C:\path\to\local\file" <upload_url>

Where:

  • form_field is the name of the form field that will receive the file.
  • C:\path\to\local\file is the Windows file path to the local file you want to upload.
  • upload_url is the URL where you want to send the file.

For example:

$ curl -F "file=@C:\Users\Username\Documents\mydocument.pdf" https://example.com/upload

Время на прочтение9 мин

Количество просмотров223K

Curl (client URL) — это инструмент командной строки на основе библиотеки libcurl для передачи данных с сервера и на сервер при помощи различных протоколов, в том числе HTTP, HTTPS, FTP, FTPS, IMAP, IMAPS, POP3, POP3S, SMTP и SMTPS. Он очень популярен в сфере автоматизации и скриптов благодаря широкому диапазону функций и поддерживаемых протоколов. В этой статье мы расскажем, как использовать curl в Windows на различных примерах.

▍ Установка в Windows

Во всех современных версиях Windows, начиная с Windows 10 (версия 1803) и Server 2019, исполняемый файл curl поставляется в комплекте, поэтому ручная установка не требуется. Чтобы определить местоположение curl и его версию в системе, можно использовать следующие команды:

where curl
curl --version

Определение местоположения и версии curl в Windows

Команда curl —version также выводит список протоколов и функций, поддерживаемых текущей версией curl. Как видно из показанного выше скриншота, к использованию встроенной утилиты curl всё готово. Если вместо этого отображается сообщение об ошибке, curl может быть недоступен потому, что вы используете более раннюю версию Windows (например, Windows 8.1 или Server 2016). В таком случае вам потребуется установить curl в Windows вручную.

▍ Синтаксис curl

Команда curl использует следующий синтаксис:

curl [options...] [url]

Инструмент поддерживает различные опции, которые мы рассмотрим ниже. Как и в любом инструменте командной строки, вы можете использовать для получения справки команду curl —help.

Получение справки при помощи команды curl

Для получения подробной справки можно использовать команду curl —help all. Справка разделена на категории, поэтому при помощи curl —help category можно просмотреть все темы.

Ознакомившись с синтаксисом curl, давайте рассмотрим различные способы применения этого инструмента на примерах.

▍ HTTP-запрос GET

При использовании curl с URL и без указания опций запрос по умолчанию использует метод GET протокола HTTP. Попробуйте выполнить такую команду:

curl https://4sysops.com

Приведённая выше команда по сути эквивалентна curl —request GET 4sysops.com, отправляющей запрос GET к 4sysops.com по протоколу HTTPS. Чтобы указать версию протокола HTTP (например, http/2), используйте опцию —http2:

curl --http2 https://4sysops.com

В случае URL, начинающихся с HTTPS, curl сначала пытается установить соединение http/2 и автоматически откатывается к http/1.1, если это не удаётся. Также он поддерживает другие методы, например, HEAD, POST, PUT и DELETE. Для использования этих методов вместе с командой curl нужно указать опцию —request (или -X), за которой следует указание метода. Стоит заметить, что список доступных методов зависит от используемого протокола.

▍ Получение информации об удалённом файле

Если вы администратор, то иногда вам могут быть интересны только заголовки HTTP. Их можно получить при помощи опции —head (или -I). Иногда URL может перенаправлять пользователя в другую точку. В таком случае опция —location (или -L) позволяет curl выполнять перенаправления. Также можно использовать —insecure (или -k), чтобы разрешить незащищённые подключения и избежать ошибок с сертификатом TLS в случае, если целевой URL использует самоподписанный сертификат. Пользуйтесь этой опцией только при абсолютной необходимости. Все эти три опции можно скомбинировать в одну краткую запись, как показано в следующей команде:

curl -kIL 4sysops.com

Опции просмотра заголовков запросов, включения незащищённого соединения и использования перенаправлений

Как можно заметить, такая краткая запись особенно полезна для комбинирования нескольких опций. Приведённая выше команда по сути эквивалентна команде curl —insecure —head —location 4sysops.com.

Опция —head (или -I) также даёт основную информацию об удалённом файле без его скачивания. Как показано на скриншоте ниже, при использовании curl с URL удалённого файла он отображает различные заголовки, дающие информацию об удалённом файле.

curl -IL https://curl.se/windows/dl-7.85.0_5/curl-7.85.0_5-win64-mingw.zip

Использование curl для просмотра основной информации удалённых файлов

Заголовок Content-Length обозначает размер файла (в байтах), Content-Type сообщает о типе медиафайла (например, image/png, text/html), Server обозначает тип серверного приложения (Apache, Gunicorn и так далее), Last-Modified показывает дату последнего изменения файла на сервере, а заголовок Accept-Ranges обозначает поддержку частичных запросов для скачивания от клиента, что по сути определяет возможность продолжения прерванной загрузки.

▍ Скачивание файла

Для скачивания файла и сохранения с тем же именем, что и на сервере, можно использовать curl с опцией —remote-name (или -O). Показанная ниже команда скачивает последнюю версию curl для Windows с официального сайта:

curl -OL https://curl.se/windows/latest.cgi?p=win64-mingw.zip

Скачивание файла с именем по умолчанию и индикатором прогресса

При необходимости для нахождения ресурса добавляется опция -L, разрешающая перенаправления. Если нужно сохранить файл с новым именем, используйте опцию —output (или -o). Кроме того, при использовании команды curl в скрипте может понадобиться отключить индикатор прогресса, что можно сделать при помощи опции —silent (или -s). Эти две опции можно скомбинировать:

curl -sLo curl.zip https://curl.se/windows/latest.cgi?p=win64-mingw.zip

Silently download a file and save with a custom name using curl

Скачивание файла без индикатора и сохранение под произвольным именем

▍ Продолжение прерванного скачивания

Наличие Accept-Ranges: bytes в заголовке ответа в буквальном смысле обозначает, что сервер поддерживает скачивания с возможностью продолжения. Чтобы продолжить прерванное скачивание, можно использовать опцию —continue-at (или -C), получающую смещение (в байтах). Обычно указывать смещение непросто, поэтому curl предоставляет простой способ продолжения прерванной загрузки:

curl -OLC - https://releases.ubuntu.com/22.04/ubuntu-22.04.1-desktop-amd64.iso

Продолжение прерванного скачивания

Как видно из скриншота, я скачивал iso-файл Ubuntu, но скачивание было прервано. Затем я снова запустил команду curl с опцией -C, и передача продолжилась с того диапазона байтов, на котором была прервана. Знак минус () рядом с -C позволяет curl автоматически определить, как и где продолжить прерванное скачивание.

▍ Аутентификация с Curl

Также Curl поддерживает аутентификацию, что позволяет скачать защищённый файл, предоставив учётные данные при помощи опции —user (or -u), принимающей имя пользователя и пароль в формате username:password. Если не вводить пароль, curl попросит ввести его в режиме no-echo.

curl -u surender -OL https://techtutsonline.com/secretFiles/sample.zip

Скачивание файла с аутентификацией по имени пользователя и паролю

Если вы используете Basic authentication, то необходимо передать имя пользователя и пароль, а значит, воспользоваться защищённым протоколом наподобие HTTPS (вместо HTTP) или FTPS (вместо FTP). Если по каким-то причинам приходится использовать протокол без шифрования, то убедитесь, что вы используете способ аутентификации, не передающий учётные данные в виде простого текста (например, аутентификацию Digest, NTLM или Negotiate).

Также curl поддерживает использование файлов конфигурации .curlrc, _curlrc и .netrc, позволяющих задавать различные опции curl в файле, а затем добавлять файл в команду при помощи опции curl —config (или curl -K), что особенно полезно при написании скриптов.

▍ Выгрузка файла

Опция —upload-file (или -T) позволяет выгружать локальный файл на удалённый сервер. Показанная ниже команда выгружает файл из локальной системы на удалённый веб-сервер по протоколу FTPS:

curl -kT C:\Users\Surender\Downloads\sample1.zip -u testlab\surender ftps://192.168.0.80/awesomewebsite.com/files/

Выгрузка файла на удалённый сервер

Опция -k добавляется для устранения проблем с сертификатами на случай, если веб-сервер использует самоподписанный сертификат. Наклонная черта в конце URL сообщает curl, что конечная точка является папкой. Можно указать несколько имён файлов, например «{sample1.zip,sample2.zip}». Ниже показано, как с помощью одной команды curl можно выгрузить на сервер несколько файлов:

curl -kT sample[1-5].zip -u testlab\surender ftps://192.168.0.80/awesomewebsite.com/files/

Выгрузка нескольких файлов на сервер

▍ Последовательность команд

Как говорилось ранее, curl поддерживает различные методы в зависимости от используемого протокола. Дополнительные команды можно отправлять при помощи —quote (или -Q) для выполнения операции до или после обычной операции curl. Например, можно скачать файл с удалённого сервера по протоколу FTPS и удалить файл с сервера после успешного скачивания. Для этого нужно выполнить следующую команду:

curl -u testlab\surender -kO "ftps://192.168.0.80/awesomewebsite.com/files/sample1.zip" -Q "-DELE sample1.zip"

Удаление файла после успешного скачивания

В показанном выше примере я скачал файл sample1.zip с FTPS-сервера при помощи опции -O. После опции -Q я добавил минус (-) перед командой DELE, что заставляет curl отправить команду DELE sample1.zip сразу после успешного скачивания файла. Аналогично, если вы хотите отправить команду на сервер до выполнения операции curl, используйте плюс (+) вместо минуса.

▍ Изменение user-agent

Информация user-agent сообщает серверу тип клиента, отправляющего запрос. При отправке запроса curl на сервер по умолчанию используется user-agent curl/<version>. Если сервер настроен так, чтобы блокировать запросы curl, можно задать собственный user-agent при помощи опции —user-agent (или -A). Показанная ниже команда отправляет стандартный user-agent Google Chrome:

curl -kIA "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0" https://awesomewebsite.com/files/secretFile.zip

Использование собственного user-agent с командой curl, чтобы избежать блокировки сервером

На показанном выше скриншоте видно, что обычный запрос curl был отклонён веб-сервером (с ответом 403 Forbidden), но при передаче другого user-agent запрос выполняется успешно, возвращая ответ 200 OK.

▍ Отправка куки

По умолчанию запрос curl не отправляет и не сохраняет куки. Для записи куки можно использовать опцию —cookie-jar (или -c), а отправить куки можно опцией —cookie (or -b):

curl -c /path/cookie_file https://awesomewebsite.com/
curl -b /path/cookie_file https://awesomewebsite.com/

Первая команда записывает файл куки, а вторая отправляет куки с запросом curl. Также можно отправить куки в формате ‘name = value’:

curl -b 'session=abcxyz' -b 'loggedin=true' http://echo.hoppscotch.io

Отправка нескольких куки командой curl

Я воспользовался веб-сайтом echo.hoppscotch.io для демонстрации заголовков HTTP-запросов, которые обычно невидимы клиентам, отправляющим запрос. Если вы не хотите пользоваться этим веб-сайтом, то можете применить опцию –verbose (или -v) для отображения запроса в сыром виде (который отображает и заголовки запросов).

▍ Использование прокси-сервера

Если вы пользуетесь прокси-сервером для подключения к интернету, в curl можно указать прокси опцией —proxy (или -x). Если прокси-сервер требует аутентификации, то добавьте —proxy-user (или -U):

curl -x 192.168.0.250:8088 -U username:password https://awesomewebsite.com/

Прокси-сервер указывается в формате server:port, а пользователь прокси — в формате username:password. Можно не вводить пароль пользователя прокси, тогда curl попросит ввести его в режиме no-echo.

Использование прокси-сервера и аутентификации

▍ Дополнительные заголовки запросов

Иногда вместе с запросом к серверу необходимо отправить дополнительную информацию. В curl это можно сделать при помощи —header (или -H), как показано в следующей команде:

curl -vkIH "x-client-os: Windows 11 Enterprise (x64)" https://awesomewebsite.com

Указание дополнительных заголовков для запроса curl

Можно отправлять любую информацию, недоступную через стандартные заголовки HTTP-запросов. В этом примере я отправил название своей операционной системы. Также я добавил опцию -v для включения verbose-вывода, отображающего дополнительный заголовок, отправляемый вместе с каждым моим запросом curl.

▍ Отправка электронного письма

Так как curl поддерживает протокол SMTP, его можно использовать для отправки электронного письма. Показанная ниже команда позволяет отправить электронное письмо при помощи curl:

curl --insecure --ssl-reqd smtps://mail.yourdomain.com –-mail-from sender@yourdomain.com –-mail-rcpt receiver@company.com --user sender@yourdomain.com --upload-file email_msg.txt

Отправка электронного письма командой curl

Давайте вкратце перечислим использованные здесь опции:

  • Опция —insecure (или -k) используется, чтобы избежать ошибки сертификата SSL. Мы уже применяли её ранее.
  • Опция —ssl-reql используется для апгрейда соединения передачи простого текста до зашифрованного соединения, если оно поддерживается SMTP-сервером. Если вы уверены, что ваш SMTP-сервер поддерживает SSL, то можно использовать непосредственно имя сервера smtps (например, smtps://smtp.yourdomain.com), как показано на скриншоте.
  • Опция —mail-from используется для указания адреса электронной почты отправителя.
  • Опция mail-rcpt указывает адрес электронной почты получателя.
  • Опция —user (или -u) отправляет имя пользователя для аутентификации, оно должно совпадать с адресом mail-from, потому что в противном случае письмо может быть отклонено или помечено как спам.
  • Опция —upload-file (или -T) используется для указания файла, в котором находится отправляемое письмо.

На скриншоте ниже показано письмо, полученное мной во входящие:

Просмотр письма, отправленного с помощью curl

Это всего лишь несколько примеров использования curl — на самом деле их гораздо больше. Я настоятельно рекомендую проверить справку по curl и поэкспериментировать с ней.

А вы используете curl? И если да, то для чего?

Telegram-канал с полезностями и уютный чат

The cURL command, or “Client for URLs“, is a useful tool you can use to move data around on the internet, working with lots of different ways of communicating online like HTTP, HTTPS, FTP, and more. It’s very useful for users who work with networks and computers a lot.

If you’re using Windows 10 or Windows 11, you can use cURL directly in the Command Prompt; you don’t need to install anything else. This guide will show you how to use cURL on Windows 11 to do all sorts of things like downloading and uploading files, sending emails, dealing with cookies and HTTP headers, and handling SSL certificates.

Run cURL Commands in Windows 11 Examples

Checking if cURL is ready on Windows 11

First, we will make sure whether cURL already exists on your computer. Just open Command Prompt and type this:

curl --version

Verifying cURL Installation in Windows 11

This command will tell you which version of cURL you have. If the command doesn’t show anything but returns an error, it means your PC does not have cURL installed yet.

Also see: How to use FTP via Command Line (CMD) on Windows 11

How to download files with cURL

One of the first things people use cURL for is to download files from the internet. It’s pretty straightforward. To download a file, you just use the -O (or --remote-name) option with the file’s URL:

curl -O https://example.com/myfile.txt

This command pulls the file myfile.txt from example.com and puts it where you are right now on your computer.

Downloading Files with cURL in Windows CMD

If you want to save the file under a different name, just use the -o (or --output) option like this:

curl -o renamedfile.txt https://example.com/myfile.txt

With the -o option and a new filename, you can choose what the downloaded file is called.

Related resource: How to Download an FTP File Using CMD in Windows 11/10

Uploading files with cURL

cURL also lets you send (upload) files to a server using different methods like FTP. The following steps will show you how to do it with FTP:

curl -T localfile.txt ftp://example.com/ --user username:password

Uploading a File using cURL

This command line will upload localfile.txt from your computer to example.com. Just replace username:password with your login info for the FTP server.

Sending emails with cURL

You can also use cURL to send emails using the SMTP protocol, which is very good for automated emails. Below a quick example:

curl --url smtps://smtp.example.com --ssl-reqd --mail-from [email protected] --mail-rcpt [email protected] --upload-file email.txt --user username:password

In this case, email.txt is a file that has your email’s subject, headers, and body. Just swap in your details for the SMTP server and the email addresses.

Sending an Email with cURL in Windows 11

Handling cookies with cURL

When you need to work with cookies, cURL can also do that. You can send cookies with the -b (or --cookie) option, and save them with the -c (or --cookie-jar) option. Here’s how to send a cookie:

curl -b "name=value" https://example.com

And to save cookies from a server into a file, do this:

curl -c cookies.txt https://example.com

Managing Cookies with cURL command in Windows

Setting up HTTP headers with cURL

Sometimes you need to tell the server more about what you’re sending, and that’s where HTTP headers come in. With cURL, you can add these headers to your request like so:

curl -H "Content-Type: application/json" -H "Authorization: Bearer your_token" https://api.example.com

Setting HTTP Headers with cURL command in Windows 11

Checking SSL certificates

cURL can help you make sure SSL certificates are valid, which is important for secure web browsing. To check a certificate, you can use this:

curl -vI https://example.com 2>&1 | findstr "expire date"

This command gets the SSL certificate details from the server and looks for the expiration date, helping you ensure everything’s up to date and secure.

Linked issue: Fixing Website’s Security Certificate Error on Windows 11/10

Making POST requests with cURL

When you need to send data to a server, you might use a POST request. Doing this with cURL is easy. For example, if you want to send JSON data to an API, you could do it like this:

curl -d "{'key1':'value1', 'key2':'value2'}" -H "Content-Type: application/json" -X POST https://api.example.com

The -d option lets you specify the data you’re sending, and the -H option tells the server it’s in JSON format. The -X tells cURL this is a POST request.

cURL and REST APIs

cURL is also very useful for working with REST APIs, which use standard web methods like GET, POST, PUT, and DELETE. We’ve looked at GET (for downloading files) and POST (for sending data). Now for updating things, you’d use a PUT request like this:

curl -d "{'key1':'value1', 'key2':'value2'}" -H "Content-Type: application/json" -X PUT https://api.example.com/resource/1

And if you need to remove something, a DELETE request does the job:

curl -X DELETE https://api.example.com/resource/1

Some final thoughts

Using cURL from the Command Prompt in Windows 11 is not just easy; it’s a powerful way to talk directly with web services from your computer. Whether you’re automating tasks, testing servers, or doing a whole bunch of other web-related activities, cURL is a very useful tool that’s available across different platforms, making your work portable and widely usable.

If you ever get stuck with a cURL command or need a quick reminder on how to use it, just pop open the command line and type curl --help. Think of it as a mini-guide that’s always there when you need it, showing you all the commands and parameters you can use with curl.

Run cURL commands in Windows

Uploading files over HTTP POST, multipart forms, or FTP is common. cURL supports these methods and simplifies file transfers, whether for images, documents, or binary data.

By using —form, files can be sent as multipart/form-data. For raw transfers or FTP, cURL manages content types and authentication automatically.

Mastering file uploads with cURL aids integration with APIs, web services, and remote servers. Automation and scripting reduce manual effort and enable rapid development workflows.

  1. Open a terminal.

  2. Upload a file using a form-based POST request.

    $ curl --form "file=@/path/to/yourfile.txt" "https://www.example.com/upload"
    {
      "status": "uploaded"
    }

    —form sends files as multipart/form-data.

  3. Upload multiple files by specifying multiple —form options.

    $ curl --form "file1=@/path/to/file1.txt" --form "file2=@/path/to/file2.jpg" "https://www.example.com/upload"

    Repeat —form for each file.

  4. Upload a file over FTP using —upload-file and —user.

    $ curl --upload-file "/path/to/yourfile.txt" "ftp://ftp.example.com" --user username:password

    Authenticate as needed for FTP transfers.

  5. Include additional form data along with the file.

    $ curl --form "file=@/path/to/yourfile.txt" --form "description=Test upload" "https://www.example.com/upload"

    Add metadata to simulate complex forms.

  6. Verify success by reviewing the response.

    $ curl --form "file=@/path/to/yourfile.txt" "https://www.example.com/upload" --verbose

    —verbose confirms the request and server response.

Discuss the article:

Comment
anonymously. Login not required.

How to Upload File Using cURL

Anyone who has ever used a terminal on Unix-like systems, or even Windows based systems is familiar with cURL. cURL, short for Client URL is a powerful and very useful command-line utility and library for transferring data using various network protocls.

cURL supports a plethora of network protocols such as HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP, FILE, among others.

Whether you want to download files, upload file, send API requests, etc from the command-line, cURL is probably one of the most powerful and efficient tool to use.

A common task when working in the terminal is uploading files using various protocols such as FTP, etc. In this tutorial, we are going to show you how you can use cURL to upload files to various endpoints such as API, AWS S3, Google Storage Bucket, and more.

cURL Upload File General Syntax

To upload a file with cURL, you can use HTTP POST method followed by the -F otopn as shown in the syntax below:

curl -F "<field=@path_to_local_File>"<url>

In the syntax above:

  1. field — this specifies the name of the form field that will recieve the file.
  2. path_to_local_file — specifies the path to the local file we wish to upload.
  3. url — specifies the URL where we want to upload the file.

An example is as shown:

curl -F "file=@sample.txt" https://example.com/upload

The command above will send an HTTP POST request to the specified URL with the form field named file and containing the contents of the PDF file.

NOTE; This technique only applies when uploading files via HTTP or HTTPS protocols. This cannot work with protocols such as FTP or SFTP.

Upload Using HTTP PUT

You are probably familiar with the HTTP PUT method. We can also use it to upload a file using cURL by the use of the -T flag. The command syntax is as shown:

curl -T <path_to_local_file> <url>

Where:

  • path_to_local_file — specifies path to the local file we wish to upload.
  • url — specifies the URL where we wisht o send the file.

An example is as shown:

curl -T ./sample.txt https://example.com/upload

The command above should send an HTTP PUT request to the specified URL with the specified file as the message body.

Upload FIle to FTP Server

Mainly when we are dealing with files, we are working with a dedicated FTP server hosted somewhere. Luckily in cURL, we can use the command syntax below to upload file to an FTP server.

curl -T <path_to_local_file> -u <username>:<password>ftp://<ftp_server_url>/<remote_directory>/

In the above syntax:

  • path_to_local_file— specifies the path to the local file we wish to upload.
  • username — sets the username for the FTP server.
  • password — specifies the associated password for the target username.
  • ftp_server_url— sets teh URL to the FTP server to which you wish to connect.
  • remote_directory — specifies the directory on the FTP server where the file will be uploaded.

An example is as shown:

curl -T ./sample.txt -u admin:password ftp://ftp.example.com/uploads/

This should connect to the specified FTP server and upload the file. It is good to ensure that you provide the correct credentials to the server and have write permissions on the specified directory,

Upload File SFTP Server

SFTP or SSH File Transfer Protocol or Secure File Protocol is a file tranfer and management protocol over secure and reliable data stream using SSH. This ensures that the commands and credentials are encrypted which makes it much secure than regular FTP.

In cURL, we can upload a file to SFTP server using the command syntax below:

curl -T <path_to_local_file> sftp://<username>@<sftp_server_url>/<remote_directory>/

In the command syntax above:

  • path_to_local file — this sets the path to the local file we wish to upload.
  • username — specifies the username to the SFTP server.
  • sftp_server_url — defines the URL of the SFTP server to which we wish to connect.
  • remote_directory — sets the remote directory on the SFTP server to which we wish to upload the file.

An example is as shown:

curl -T ~/sample.txt sftp://admin@sftp.example.com/uploads/

Upload to Amazon S3 Bucket (Pre-Signed)

Amazon S3 provides us with a feature called pre-signed URL which is a way of generating a temporary access to an object in the S3 bucket.

We can use presigned URL to upload file via cURL as shown:

curl -X PUT -F sample.txt  https://pre-signed-url

This should upload the specified file to the specified URL using your AWS S3 creds.

Upload File to Artifactory

We can also use cURL to upload files such as binaries to Artifactory using the command as shown:

$ curl -u <username>:<password> -T "<path_to_local_file>" "<artifactory_url>/artifactory/<repository>/<target_path>/<filename>"

In this syntax:

  • username — sets the Artifactory username
  • password — password associated with your Artifactory username.
  • path_to_local_file — specifies path to the local file we wish to upload.
  • artifactory_url — specifies the URL to target Artifactory instance.
  • repository — defines the Artifactory repository where to store the file.
  • target_path — this is an optional directory path within the specified repository on where to store the file.
  • filename — specifies the name we wish to assign the uploaded file.

This should allow you to upload a specified file to an Artifactory instance.

Upload File to Google Storage Bucket

To upload a file to a Google Cloud Storage bucket using the cURL command, we can use an authenticated POST request with the appropriate headers for authorization.

Before that, we need to setup an OAuth 2.0 token for authentication. This requires setting up a Google Cloud project, enabling the Google Cloud Storage API, and obtaining credentials.

Once configured, we can run the command as shown below to upload the file:

curl -X POST --data-binary @local-file-path \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: file-content-type" \
  "https://storage.googleapis.com/upload/storage/v1/b/YOUR_BUCKET_NAME/o?uploadType=media&name=remote-file-name"

Where:

  • local-file-path — specifies the path to the file we wish to upload.
  • YOUR_ACCESS_TOKEN — sets the OAuth 2.0 access token created earlier.
  • file-content-type — this defines the MIME type of the file we are uploading, such as image/jpeg for JPEG images, etc.
  • YOUR_BUCKET_NAME — defines the name of the Google Cloud Storage bucket.
  • remote-file-name — sets the desired name of the file once it’s uploaded to the bucket.

Conclusion

In this tutorial, we learned how we can use cURL to upload files to various protocols such as HTTP, HTTPS. FTP, SFTP, Amazon S3, Artifactory, and more.

:) Cheers!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Журнал системных ошибок windows 10
  • Как войти в безопасности режим windows 10 при включении компьютера
  • Skachat google play market na windows 10
  • How to change dns windows 10
  • Утилита lenovo utility for windows 10