0

I am trying to upload an image from URL to Google Drive Folder using GDrive API in Python.

I am trying to directly fetch the image data and upload it to drive without saving it locally. Through my research I came to know about BytesIO but it is giving the following error

main.py

import requests
import os
import io
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from dotenv import load_dotenv
import os
load_dotenv()
from io import BytesIO

import tempfile
# Authenticate and create the PyDrive client
gauth = GoogleAuth()
drive = GoogleDrive(gauth)

# Set the ID of the folder you want to upload the file to
folder_id = "1GUUQO5huBXFQfsx_on7DdDDmkHnrZIsd"

# Set the URL of the image you want to fetch
url = "image URL"

# Set the authorization header using the API key stored in environment variables
headers = {"Authorization": os.getenv("API")}

# Fetch the image data from the URL
response = requests.get(url, headers=headers)

# Check if the response status code is OK (200)
#if response.status_code == 200:
    # Create a BytesIO object and write the image data to it
    #  with io.BytesIO(response.content) as fp:
    #     fp.seek(0)
    #     file = drive.CreateFile({'title': 'hello2.jpg', 'parents': [{'id': folder_id}]})
    #     file.SetContentFile(fp)
    #     file.Upload()
    headers = {'Authorization': os.getenv("API")}
    response = requests.get(url, headers=headers)

headers = {'Authorization': os.getenv("API")}
response = requests.get(url, headers=headers)

if response.status_code == 200:
# Create a BytesIO object and write the image data to it
    with BytesIO(response.content) as fp:
    # Set the file name for the image
        filename = 'hello2.jpg'
        
        # Create a new file in Google Drive and upload the image data
        file = drive.CreateFile({'title': filename, 'parents': [{'id': folder_id}]})
        file.SetContentFile(fp)
        file.Upload()
        print(f'Image {filename} uploaded to Google Drive successfully.')
else:
    print("Error fetching image data", response.status_code)

Error/ Output:

TypeError: expected str, bytes or os.PathLike object, not BytesIO

I tried fp.getValue(), fp.read() but wasn't able to solve the error

Any help or advice is appreciated, Thank you

Dummy Cron
  • 143
  • 2
  • 11

0 Answers0