简体   繁体   中英

Unable to upload files using Google Drive API in python

I want to upload files from my local folder to Google Drive using Google Drive API in Python.

Currently, I am facing this error:

Traceback (most recent call last):
  File "c:\Users\ice\projects\testproject\googledrive_api.py", line 72, in <module>
    service.files().create(
  File "C:\Users\ice\AppData\Local\Programs\Python\Python38-32\lib\site-packages\googleapiclient\_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\ice\AppData\Local\Programs\Python\Python38-32\lib\site-packages\googleapiclient\http.py", line 915, in 
execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/upload/drive/v3/files?fields=id&alt=json&uploadType=multipart returned "File not found: 18JvVkD3wy79bZ039viXEt1J2AP3f5Iqm.">

Here are my codes:

import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from oauth2client.client import GoogleCredentials
from Google import Create_Service
from googleapiclient.http import MediaFileUpload

# Authentication and list files in Google Drive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)

fileList = drive.ListFile(
    {'q': "'1Gnv3rIbBG1-xwtk6PIidqB02XkeoUEvc' in parents and trashed=false"}).GetList()
for file1 in fileList:
    print('title: %s, id: %s' % (file1['title'], file1['id']))

# Upload file(s) to Google Drive
CLIENT_SECRET_FILE = 'client_secrets.json'
API_NAME = 'drive'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/drive']

service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)

# ID of the destination folder
folder_id = '18JvVkD3wy79bZ039viXEt1J2AP3f5Iqm'

# 1st list for file names, 2nd list for file types
file_names = ['age.pdf', 'age.png']
mime_types = ['application/pdf', 'image/png']

for file_name, mime_type in zip(file_names, mime_types):
    file_metadata = {
        'name': file_name, 
        'parents': [folder_id]
    }

    media = MediaFileUpload('./{0}'.format(file_name), mimetype=mime_type)

    service.files().create(
        body=file_metadata,
        media_body=media,
        fields='id'
    ).execute()

I really can't figure out how to solve this issue. I appreciate your help. Thank you.

Use this supportsTeamDrives=True param in create function

Like this

service.files().create(
        supportsTeamDrives=True,
        body=file_metadata,
        media_body=media,
        fields='id'
    ).execute()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM