我可以使用this example类使用MediaUpload
中提供的python API将文件上传到Google云端硬盘。
但是我需要上传一个动态创建的文件,我不想保存并再次打开。
尚无此类实现。 This guide说我需要创建MediaUpload的子类,并且必须完全实现MediaUpload
接口。
我遍历了代码,这确实令人困惑。如果有人已经实现它或可以帮助我,请共享代码。
谢谢
回答我自己的问题
我想做的是从URL获取文件并上传到驱动器。
使用MediaIoBaseUpload
类而不是MediaUpload
类。
response = urllib2.urlopen(url)
fh = BytesIO(response.read())
media_body = MediaIoBaseUpload(fh, mimetype='image/jpeg',
chunksize=1024*1024, resumable=True)
body = {
'title': 'pic.jpg'
}
drive_service.files().insert(body=body, media_body=media_body).execute()
对于那些正在寻找一种上载文件的方法,[,但是使用formdata或bytes中的任何媒体对象/字符串,这是示例代码。
以下情况是,我正在使用formdata从前端应用程序发送docx文件,并在后端接收它。现在,此文件,我想上传到Google驱动器。我正在使用的技术堆栈是Angular 8(前端)和Tornado Python(后端)。
[后端Python代码:
import io
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
from gdrive_config import credentials # Import your credentials object created using a service account
# Refer this link for more info - https://github.com/googleapis/google-api-python-client/blob/master/docs/oauth-server.md
drive_service = build("drive", "v3", credentials=credentials, cache_discovery=False)
file = self.request.files
file_info = file["my_docx_file"][0] # Here "my_docx_file" is the key name you have set in form data
def upload_file(file_info):
file_name = file_info["filename"]
file_metadata = {
"name": file_name,
"mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", # Mimetype for docx
}
media = MediaIoBaseUpload(io.BytesIO(file_info["body"]), # **Pass your bytes object/string here
mimetype="application/vnd.google-apps.document", # I'm converting docx to native google docs
resumable=True)
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields="id, name").execute()
print("Uploaded File '{}' with ID: {}".format(file.get("name"), file.get("id")))
参考链接:服务帐户的Oauth流-https://github.com/googleapis/google-api-python-client/blob/master/docs/oauth-server.md
Google驱动器python客户端文档-https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.files.html
Google云端硬盘上传文件指南-https://developers.google.com/drive/api/v3/manage-uploads