Python Google Drive API,上传内存中的数据而不是磁盘上的文件?

Gee*_*ek4 4 python python-3.x google-drive-api

我一直在搜索论坛,但没有成功解决我的问题。

我正在尝试使用 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!")
Run Code Online (Sandbox Code Playgroud)

但是,我想做这样的事情:

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.
Run Code Online (Sandbox Code Playgroud)

由于我正在执行的操作,该文件将在内存中,因此无需保存到磁盘,使用文件路径上传文件,然后删除临时保存在磁盘上的文件。

如何只上传内存中的文件而不必将其保存到磁盘并使用文件路径和名称?

谢谢

Tan*_*ike 5

  • 您想使用 googleapis 和 python 将内存中的数据上传到 Google Drive。
  • 您要使用fileInMemory以下脚本。

    with open('MyFile.jpeg', 'rb') as FID: 
        fileInMemory = FID.read()
    
    Run Code Online (Sandbox Code Playgroud)
  • 您已经能够使用 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!")
Run Code Online (Sandbox Code Playgroud)

参考: