Reputation: 173
I'm trying to upload a jpg file onto google drive using the api but i'm not having much luck. Although the code does run without errors, the "image" saved in my google drive is untitled and doesn't actually contain data.
Here's how I'm doing it right now in Python:
post_body = "grant_type=refresh_token&client_id={}&client_secret={}&refresh_token={}".format(client_id, client_secret, refresh_token)
r = requests.post(refresh_url, data=post_body, headers={"Content-Type" : "application/x-www-form-urlencoded"})
r_json = json.loads(r.text)
access_token = r_json["access_token"]
media = MediaFileUpload(filename, mimetype="image/jpeg", resumable=True)
body = {
"name" : filename,
"mimeType" : "image/jpeg"
}
drive_url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
drive_r = requests.post(drive_url, data=body, headers={"Authorization": "Bearer " + access_token, "Content-type": "image/jpeg"})
When I print drive_r.text, the response I'm getting back is this:
{
"kind": "drive#file",
"id": "1Vt4gP***************",
"name": "Untitled",
"mimeType": "image/jpeg"
}
Upvotes: 0
Views: 229
Reputation: 201378
From your script, I understood that you want to upload a file to Google Drive without using googleapis for Python. In this case, I would like to propose the following modification.
uploadType=media
. But it seems that you want to include the file metadata. In this case, please use uploadType=multipart
.If the file size you want to upload is less than 5 MB, you can use the following script. uploadType=multipart
is used.
import json
import requests
access_token = r_json["access_token"] # This is your script for retrieving the access token.
filename = '###' # Please set the filename with the path.
para = {"name": filename}
files = {
'data': ('metadata', json.dumps(para), 'application/json'),
'file': open(filename, "rb")
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers={"Authorization": "Bearer " + access_token},
files=files
)
print(r.text)
If the file size you want to upload is more than 5 MB, you can use the following script. uploadType=resumable
is used.
import json
import os
import requests
access_token = r_json["access_token"] # This is your script for retrieving the access token.
filename = '###' # Please set the filename with the path.
filesize = os.path.getsize(filename)
params = {
"name": filename,
"mimeType": "image/jpeg"
}
r1 = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
headers={"Authorization": "Bearer " + access_token, "Content-Type": "application/json"},
data=json.dumps(params)
)
r2 = requests.put(
r1.headers['Location'],
headers={"Content-Range": "bytes 0-" + str(filesize - 1) + "/" + str(filesize)},
data=open(filename, 'rb')
)
print(r2.text)
Upvotes: 1