是否可以将字符串而不是文件本身上传到Google云端硬盘?在this示例中,脚本假定存在物理文件'files/photo.jpg'
。如何将csv文件或json文件物理上不在我的机器上上传?
这是上面示例中的内容
folder_id = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E'
file_metadata = {
'name': 'photo.jpg',
'parents': [folder_id]
}
media = MediaFileUpload('files/photo.jpg',
mimetype='image/jpeg',
resumable=True)
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print 'File ID: %s' % file.get('id')
但是我想将'files/photo.jpg'
而不是文件{'somekey' : 'somevalue'}
上传为json文件。
答案 0 :(得分:0)
最简单的方法是将JSON字符串写到本地文件(可能在/ tmp中)并上传。
答案 1 :(得分:0)
如果我的理解是正确的,那么该修改如何?请认为这只是几个答案之一。
使用此功能时,请设置folder_id
。
mimeType = 'text/csv'
text = 'a1, b1, c1\na2, b2, c2'
media = MediaIoBaseUpload(io.BytesIO(text.encode('utf-8')), mimetype=mimeType, resumable=True)
file_metadata = {'name': 'sampleName', 'parents': [folder_id], 'mimeType': mimeType}
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
text
作为JSON文件上传。请修改mimeType和文本。答案 2 :(得分:0)
对于那些正在寻找一种上传方式的人,这里是一个示例。
以下情况是,我正在使用formdata从前端应用程序发送文本文件并在后端接收它。现在,这个文件,我想上传到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_text_file"][0] # Here "my_text_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": "text/plain", # Mimetype for text file
}
# If you print file_info, you will notice your text file data will be in the body & of type bytes.
media = MediaIoBaseUpload(io.BytesIO(file_info["body"]), # **Pass your bytes object/string here.
mimetype="application/vnd.google-apps.document", # I'm converting text file to native google docs.
# Keep the mimetype "text/plain", if you want to upload it as a text file itself.
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