How to Download a File Directly to Google Drive from a Download Link
If you click a download link, it will instantly download a file to your computer. But, have you ever wanted to download a file from the internet straight to your Google Drive instead of downloading it to your computer? Today, I’m going to show you how to do this and even if you are a non-techie, you can simply follow this method.
Some web services directly allow you to copy files to Google Drive from their storage. But there are some cases, where this option isn’t available and that’s where I’ve got you covered.
We’ll run a little Python code in Google Colab online environment. The code will,
- Take the download link you provide.
- Grab the file from that link.
- Download it directly to a folder in your Google Drive.
Are you ready? Then let’s get started!
Understanding The Code
First of all, let’s get to know each part of the Python code we are going to use. If you’re not interested in the code, you can skip to Step 1.
Importing Libraries
import requests
from google.colab import drive
from google.colab import auth
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
import io
import os
from urllib.parse import urlparse, unquote
These libraries are essential to facilitate the required functions of our code.
Mounting Google Drive and Authentication
drive.mount('/content/drive')
This connects your Google Drive with Google Colab so that the code can access it.
auth.authenticate_user()
drive_service = build('drive', 'v3', cache_discovery=False)
This gives permission to copy the file to your Google Drive, which is essential for the next steps.
Defining Functions
Let’s understand what each function does.
def get_filename_from_url(url):
response = requests.head(url, allow_redirects=True)
content_disposition = response.headers.get('Content-Disposition')
if content_disposition:
import re
fname = re.findall("filename=(.+)", content_disposition)
if len(fname) > 0:
return fname[0].strip('"')
path = urlparse(url).path
filename = os.path.basename(unquote(path))
if not filename:
filename = 'downloaded_file'
return filename
This function figures out what to name your file based on the download link. It first checks if the website tells us the filename. If not, it tries to guess from the link itself. This is to make sure that your file has a proper name when it’s saved to Google Drive.
def get_or_create_folder(folder_path):
folders = folder_path.strip('/').split('/')
parent_id = 'root'
for folder in folders:
query = f"name='{folder}' and mimeType='application/vnd.google-apps.folder' and '{parent_id}' in parents and trashed=false"
results = drive_service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
items = results.get('files', [])
if not items:
file_metadata = {
'name': folder,
'mimeType': 'application/vnd.google-apps.folder',
'parents': [parent_id]
}
folder = drive_service.files().create(body=file_metadata, fields='id').execute()
parent_id = folder.get('id')
else:
parent_id = items[0]['id']
return parent_id
This function finds or creates the folder where you want to save your file in Google Drive. It checks if each folder in the path exists. If a folder doesn’t exist, it creates it. With this function, you don’t have to manually create folders in your Google Drive before downloading.
def download_to_drive(url, folder_path):
try:
filename = get_filename_from_url(url)
folder_id = get_or_create_folder(folder_path)
response = requests.get(url, stream=True)
response.raise_for_status()
file_content = io.BytesIO()
total_size = int(response.headers.get('content-length', 0))
chunk_size = 1024
for data in response.iter_content(chunk_size):
file_content.write(data)
file_content.seek(0)
file_metadata = {'name': filename, 'parents': [folder_id]}
media = MediaIoBaseUpload(file_content,
mimetype=response.headers.get('content-type'),
resumable=True)
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print(f'File ID: {file.get("id")}')
print(f'File "{filename}" has been uploaded to Google Drive in the folder: {folder_path}')
except requests.exceptions.RequestException as e:
print(f"Error downloading the file: {e}")
except Exception as e:
print(f"An error occurred: {e}")
This is the main function that manages the whole process. It gets the filename by calling the function get_filename_from_url
and finds or creates the folder by calling the function get_or_create_folder
to download the file to your Google Drive from the link.
This function also includes error handling. This means, that if there’s a problem downloading the file, or any error occurs during the process, it will let you know so that you can understand what went wrong if something didn’t work as expected.
Defining the Download Link and Google Drive Directory
url = 'link/to/file'
folder_path = 'path/to/folder'
This is where you should give the actual download link and the path to your Google Drive folder, where you want to download the file.
Calling the Function
download_to_drive(url, folder_path)
This is to call the function download_to_drive
while giving the defined link and Google Drive directory.
Now, you have a brief understanding of what the code does. Let’s follow the step-by-step process.
Step 1: Sign into Google and Open Google Colab
Firstly, you need to sign into Google and make sure you have access to your Google Drive. Then, you need to open Google Colab.
To do so, go to Google and search for ‘Google Colab’ and then click on the link: colab.research.google.com

Step 2: Create a New Notebook
Once you’re in Google Colab, you can notice that you’ve signed in with the same Google account.
Click on ‘New notebook’. This creates the notebook where we place our code and run it.

Step 3: Copy and Paste the Code
Now, you can see the Google Colab interface and find the first cell of the notebook.

You need to copy the entire code and paste it into this cell. The complete code we’ve discussed above is as follows.
# Import necessary libraries
import requests
from google.colab import drive
from google.colab import auth
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
import io
import os
from urllib.parse import urlparse, unquote
# Mount Google Drive
drive.mount('/content/drive')
# Authenticate and create the Drive API service
auth.authenticate_user()
drive_service = build('drive', 'v3', cache_discovery=False)
def get_filename_from_url(url):
# Try to get filename from Content-Disposition header
response = requests.head(url, allow_redirects=True)
content_disposition = response.headers.get('Content-Disposition')
if content_disposition:
import re
fname = re.findall("filename=(.+)", content_disposition)
if len(fname) > 0:
return fname[0].strip('"')
# Parse URL if Content-Disposition is not available
path = urlparse(url).path
filename = os.path.basename(unquote(path))
# Use a default name if filename is still empty
if not filename:
filename = 'downloaded_file'
return filename
def get_or_create_folder(folder_path):
# Split the folder path into individual folder names
folders = folder_path.strip('/').split('/')
parent_id = 'root'
for folder in folders:
# Check if the folder exists
query = f"name='{folder}' and mimeType='application/vnd.google-apps.folder' and '{parent_id}' in parents and trashed=false"
results = drive_service.files().list(q=query, spaces='drive', fields='files(id, name)').execute()
items = results.get('files', [])
if not items:
# Create the folder if it doesn't exist
file_metadata = {
'name': folder,
'mimeType': 'application/vnd.google-apps.folder',
'parents': [parent_id]
}
folder = drive_service.files().create(body=file_metadata, fields='id').execute()
parent_id = folder.get('id')
else:
# Use the existing folder
parent_id = items[0]['id']
return parent_id
def download_to_drive(url, folder_path):
try:
# Get filename from URL
filename = get_filename_from_url(url)
# Get or create the specified folder
folder_id = get_or_create_folder(folder_path)
# Download the file
response = requests.get(url, stream=True)
response.raise_for_status() # Check if the request was successful
file_content = io.BytesIO()
total_size = int(response.headers.get('content-length', 0))
chunk_size = 1024
for data in response.iter_content(chunk_size):
file_content.write(data)
file_content.seek(0)
# Prepare file metadata
file_metadata = {'name': filename, 'parents': [folder_id]}
# Create a MediaIoBaseUpload object
media = MediaIoBaseUpload(file_content,
mimetype=response.headers.get('content-type'),
resumable=True)
# Upload the file to Google Drive
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print(f'File ID: {file.get("id")}')
print(f'File "{filename}" has been uploaded to Google Drive in the folder: {folder_path}')
except requests.exceptions.RequestException as e:
print(f"Error downloading the file: {e}")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
url = 'link/to/file' # Replace with actual download link
folder_path = 'path/to/folder' # Replace with desired Google Drive folder path
download_to_drive(url, folder_path)
Step 4: Replacing the Download Link and Google Drive Directory
You need to replace `link/to/file` with the actual download link of the file that you want to download to Google Drive. For example `https://website.com/file.zip`. You can copy the download link by right-clicking on the download button on the website and then selecting ‘Copy link address’.
Then change `path/to/folder` to the Google Drive folder where you want to save the file. For example `CopyFromLink/MyFiles`.
Step 5: Running the Code
To run the code, click on the play button on the left side of the cell.
While running the code it’ll ask for permission to access your Google Drive and you have to allow it.

You need to click on ‘Connect to Google Drive’ and then select your Google account and continue.

To allow the file to be copied into your Google Drive, you have to click on ‘Allow’ and then select your Google account and continue.
After that, the code will take some time to complete running based on the file size. So, wait until it’s done.
After it completes running, you’ll see messages in the output. If successful, it will show the file ID and confirm the downloading. Now, you’ll see the downloaded file in the given Google Drive folder. If there’s an error, it will explain what went wrong.
You can reuse this Google Colab notebook whenever you want to download more files. Just change the download link and folder path each time. You can find this notebook in a folder named ‘Colab Notebooks’ inside your Google Drive.
Now, you know how to download a file straight to your Google Drive from a download link.
Sometimes this code may not work for large files. In such cases, you can use the following code. https://github.com/pabasar/file_download_to_google_drive/blob/main/code_large_files.py
Thanks for reading and hope you enjoyed it. If you find this article useful, please give a clap!