How To Perform Resumable File Upload To Google Drive With Python
Solution 1:
You almost have it done, just a couple of things:
Regarding the payload of the first request where you initiate the resumable upload and send the metadata:
payload = '{"name": "myObject", "parents": "[PARENT_FOLDER]"}'
You should put it this way to store the file in the selected folder:
payload = '{"name": "myObject2", "parents": ["PARENT_FOLDER_ID"]}'
The only change would be using the quotation marks ("") inside the brackets for each parent folder id, this is because the API is expecting an array of strings for the parents field (each string for each parent folder id) [1].
For the second part of the resumable upload (uploading the file), you just have to obtain the file you want to upload and send it as the request body with the "data" parameter in the request like this:
uri = response.headers['Location']
headers = {
'Content-Length': "2000000",
'Content-Type': "image/jpeg"
}
#Open the file and stored it in data2
in_file = open("filepath to the file", "rb") # opening for [r]eading as [b]inary
data2 = in_file.read()
#Send the file in the request
response = requests.request(
"PUT", uri, data=data2, headers=headers)
Using the function open() [2] with the file path including the filename (relative or absolute) and using "rb" as the 2nd parameter to read the file in binary mode, you will get a raw binary file (file object) and applying the read() [3] function to it you will get the binary data, which is what the request is expecting in the request body (data parameter).
I tested the code provided above uploading an image to a specific folder and it worked. Remember to change the content-type.
[1] https://developers.google.com/drive/api/v3/reference/files
Post a Comment for "How To Perform Resumable File Upload To Google Drive With Python"