如何从 URL 上传文件到 GDrive 而无需在本地保存

问题描述 投票:0回答:0

我正在尝试使用 Python 中的 GDrive API 将图像从 URL 上传到 Google 云端硬盘文件夹。

我正在尝试直接获取图像数据并将其上传到驱动器而不在本地保存。通过我的研究,我开始了解 BytesIO 但它给出了以下错误

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)

错误/输出:

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

我尝试了 fp.getValue(), fp.read() 但无法解决错误

感谢任何帮助或建议,谢谢

python file-upload python-requests google-drive-api bytesio
© www.soinside.com 2019 - 2024. All rights reserved.