Curl Download File with Original Filename

This article provides a quick and practical guide on how to use the curl command-line tool to download files from the web and save them using their original filenames. You will learn about the key flags, such as -O, -L, and -J, which allow you to automate this process and handle redirects and server-defined filenames efficiently.

Using the -O Flag to Keep the Filename

The most common way to download a file and keep its original filename is by using the uppercase -O (or --remote-name) option. This tells curl to write the output to a local file named exactly like the remote file in the URL.

curl -O https://example.com/downloads/file.zip

In this example, curl will download the file and save it locally as file.zip in your current working directory. For this method to work, the URL must end with a specific filename.

Handling Redirects with the -L Flag

If the download link redirects to another URL before delivering the file, curl might not download the file properly. To resolve this, combine the -O flag with the -L (or --location) flag. This forces curl to follow any HTTP redirects.

curl -OL https://example.com/downloads/redirect-link

Using -OL ensures that curl follows the redirection path until it reaches the final file, saving it with its original filename.

Saving Files with Server-Defined Names (-J Flag)

Sometimes, the URL does not contain the actual filename (for example, https://example.com/download?id=123). Instead, the web server specifies the filename in the HTTP response header (Content-Disposition). To tell curl to use the filename provided by the server, use the -J (or --remote-header-name) flag in combination with -O and -L.

curl -OJL https://example.com/download?id=123

This command extracts the correct filename from the server’s response headers and saves the file accordingly on your local machine.