Reputation: 173
I'm uploading a jpg file into my google drive account. It works fine, but I need it to upload to a specific folder but am not sure how to set the parents parameter in the metadata.
Here's my code:
data = {"file": open(filedirectory, 'rb').read(), "title" : filename, "parents" : [{"id": "<folderid>"}]}
drive_url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
drive_r = requests.post(drive_url, data=data, headers={"Authorization": "Bearer " + access_token, "Content-type": "image/jpeg"})
Upvotes: 2
Views: 6701
Reputation: 95
it seems I have been able to get the Javascript SDK to react, with this code
gapi.client.drive.files.create({
name: 'multapart.jpg', //OPTIONAL
uploadType: 'multipart',
},{body:'your content here',content:'your content here'})
where media is bytes representation for an image
in chronium edge it complained that
Access to XMLHttpRequest at 'https://content.googleapis.com/drive/v3/files?name=resumable.jpg&body=%EF%BF%BD%EF%....%BD&uploadType=multipart&alt=json&key=[you cant see this haha]' from origin 'https://content.googleapis.com' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
in edge legacy it said it was a malformed and when I did uploadType=media, it said is was using https://content.googleapis.com/drive/v3/files instead of https://content.googleapis.com/upload/drive/v3/files, so the JS SDK is unreliable and riddled with bugs, glad I got it to react, if only someone can find the logic to give it the right URL because I believe the js SDK is not buggy, google doesnt want ppl to use it
Upvotes: -1
Reputation: 201378
I believe your goal as follows.
requests
of python.In the case of uploadType=media
, the official document says as follows.
Simple upload (uploadType=media). Use this upload type to quickly transfer a small media file (5 MB or less) without supplying metadata. To perform a simple upload, refer to Perform a simple upload.
So in order to upload the file content and file metadata, please use uploadType=multipart
.
And also, in your endpoint, Drive API v3 is used. But "parents" : [{"id": "<folderid>"}]
is for Drive API v2. It is required to also modify it.
When your script is modified for uploadType=multipart
, it becomes as follows.
When you use this script, please set the variables of filedirectory, filename, folderid, access_token
.
import json
import requests
filedirectory = '###'
filename = '###'
folderid = '###'
access_token = '###'
metadata = {
"name": filename,
"parents": [folderid]
}
files = {
'data': ('metadata', json.dumps(metadata), 'application/json'),
'file': open(filedirectory, "rb").read() # or open(filedirectory, "rb")
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers={"Authorization": "Bearer " + access_token},
files=files
)
print(r.text)
Upvotes: 7