Josh
Josh

Reputation: 164

Unable to upload file to folder in Google Drive

I'm trying to upload a local file to a a specified folder in Google Drive, and I'm only successful in getting it uploaded to Drive, not in the folder I'm telling it to. I've tested with a shared folder as well as a non-shared folder and I'm getting the same result. No error, just the file being in the root Drive directory.


    creds = GetGoogleCredentials()
    service = build('drive', 'v3', credentials=creds)
    # Call the Drive v3 API
    FileSearch = service.files().list(q="name='{0}'".format(file), fields="nextPageToken, files(id, name)").execute()
    items = FileSearch.get('files', [])
    FolderID = 'IDHere'
    if not items:
        file_metadata = {'name': file, 
                         "parents": FolderID
                        }

        media = MediaFileUpload('folder/en/' + file,resumable=True)
        service.files().create(body=file_metadata,media_body=media,fields='id').execute()
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

Based off what I've found, the "parents": FolderID entry should be what I need, but it's like the create method is ignoring it.

Upvotes: 1

Views: 140

Answers (1)

Tanaike
Tanaike

Reputation: 201643

  • You want to upload a file to the specific folder in Google Drive using Drive API v3.
  • You want to achieve this using googleapis with python.
  • You have already uploaded a file to Google Drive using your script.

If my understanding is correct, how about this modification? Please modify parents in the object of file_metadata as follows.

From:

"parents": FolderID

To:

"parents": [FolderID]
  • At Google Drive, a file has several parents. So in this case, the folder ID is set in an array.

Reference:

If this was not the direct solution of your issue, I apologize.

Upvotes: 2

Related Questions