[英]Is there a way to rename a file while uploading it to google drive using gdrive API?
[英]Uploading file to Google Drive using resumable API
我有一个相当大的文件,我正在尝试使用 API 将其上传到谷歌驱动器。 我正在尝试使用示例图像进行学习以进行学习。 将图像上传为 multiplart 上传或单个文件上传可以毫不犹豫地工作,但是当我尝试使用可恢复上传端点执行此操作时,代码给了我一个错误:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "badContent",
"message": "Unsupported content with type: image/jpeg"
}
],
"code": 400,
"message": "Unsupported content with type: image/jpeg"
}
}
我使用的代码如下:
import requests
import os
filesize = os.path.getsize('./photo.jpeg')
print("File size is: ", filesize)
headers = {"Authorization" : "Bearer "+"<MY API KEY HERE>",
"Content-Length": str(filesize),
"Content-Type": "image/jpeg"}
params = {
"name": "sample.png",
"parents": ['1CxrbEfy5y3ZyBVF6k2IFIuOk_Z0wjZAo']
}
files = {
'data': ('metadata', json.dumps(params), 'image/jpeg'),
'file': open('./photo.jpeg', 'rb')
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
headers = headers,
files = files
)
print(r.text)
请帮忙。
photo.jpeg
图像文件。requests
来实现这一点。如果我的理解是正确的,这个答案怎么样? 请将此视为几种可能的答案之一。
在你的脚本中,
params
。https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable
。"Content-Type": "image/jpeg"
用于请求标头中。 这样,就会发生错误。'./photo.jpeg'
。 但是您尝试将文件名设置为sample.png
。 为了使用可续传上传文件,首先需要检索location
,即上传文件的URL。 这包含在响应标头中。 参考
location
后,可以将数据上传到location
的端点。 在以下示例脚本中,图像 ( image/jpeg
) 与可恢复上传一起上传。 在这种情况下,作为一个简单的测试,文件是按一个块上传的。 在你使用这个之前,请设置access_token
的变量, filename
import json
import os
import requests
access_token = '###' # Please set your access token.
filename = './photo.jpeg' # Please set the filename with path.
filesize = os.path.getsize(filename)
print("File size is: ", filesize)
# 1. Retrieve session for resumable upload.
headers = {"Authorization": "Bearer "+access_token, "Content-Type": "application/json"}
params = {
"name": "sample.jpeg",
"parents": ['1CxrbEfy5y3ZyBVF6k2IFIuOk_Z0wjZAo'],
"mimeType": "image/jpeg"
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
headers=headers,
data=json.dumps(params)
)
location = r.headers['Location']
# 2. Upload the file.
headers = {"Content-Range": "bytes 0-" + str(filesize - 1) + "/" + str(filesize)}
r = requests.put(location, headers=headers, data=open(filename, 'rb'))
print(r.text)
1CxrbEfy5y3ZyBVF6k2IFIuOk_Z0wjZAo
的父ID是否正确。如果我误解了您的问题并且这不是您想要的方向,我深表歉意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.