我一直在搜索有关我的问题的论坛,均未成功。
我正在尝试使用Google Drive Python API将内存中的文件上传到Google Drive。但是,我看到的所有示例都使用磁盘上具有特定文件路径和名称的文件。
service = build('drive', 'v3', credentials=creds)
media = MediaFileUpload(
'MyFile.jpeg',
mimetype='image/jpeg',
resumable=True
)
request = service.files().create(
media_body=media,
body={'name': 'MyFile', 'parents': ['<your folder Id>']}
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print("Uploaded %d%%." % int(status.progress() * 100))
print("Upload Complete!")
但是,我想做这样的事情:
with open('MyFile.jpeg', 'rb') as FID:
fileInMemory = FID.read()
myGDriveUpload(fileInMemory)
#Pass jpeg file that has been read into memory
#to Google Drive for upload.
由于我正在执行的操作,该文件将在内存中,并且没有必要保存到磁盘,使用文件路径上传文件,然后删除已临时保存在磁盘上的文件。
怎么可能只上载文件而不需要将其保存到磁盘并使用文件路径和名称呢?
谢谢
答案 0 :(得分:4)
您要使用以下脚本的fileInMemory
。
with open('MyFile.jpeg', 'rb') as FID:
fileInMemory = FID.read()
您已经能够使用Drive API上传文件。
在此答案中,我使用“ Class MediaIoBaseUpload”代替“ Class MediaFileUpload”。
service = build('drive', 'v3', credentials=creds)
with open('MyFile.jpeg', 'rb') as FID:
fileInMemory = FID.read()
media = MediaIoBaseUpload(io.BytesIO(fileInMemory), mimetype='image/jpeg', resumable=True)
request = service.files().create(
media_body=media,
body={'name': 'MyFile', 'parents': ['<your folder Id>']}
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print("Uploaded %d%%." % int(status.progress() * 100))
print("Upload Complete!")