如何使用Google Drive API和Python将文件上传到特定文件夹?

问题描述:

我正在将jpg文件上传到我的Google云端硬盘帐户中.它工作正常,但我需要将其上传到特定的文件夹,但不确定如何在元数据中设置parents参数.

I'm uploading a jpg file into my google drive account. It works fine, but I need it to upload to a specific folder but am not sure how to set the parents parameter in the metadata.

这是我的代码:

data = {"file": open(filedirectory, 'rb').read(), "title" : filename, "parents" : [{"id": "<folderid>"}]}
drive_url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
drive_r = requests.post(drive_url, data=data, headers={"Authorization": "Bearer " + access_token, "Content-type": "image/jpeg"})

我相信您的目标如下.

  • 您要将文件上传到Google云端硬盘中的特定文件夹.
  • 您想使用python的 requests 来实现这一目标.
  • You want to upload a file to the specific folder in Google Drive.
  • You want to achieve this using requests of python.
  • uploadType = media 的情况下,官方文件说明如下.

  • In the case of uploadType=media, the official document says as follows.

简单上传(uploadType = media).使用此上传类型可以快速传输较小的媒体文件(5 MB或更小),而无需提供元数据.要执行简单上传,请参阅执行简单上传.

Simple upload (uploadType=media). Use this upload type to quickly transfer a small media file (5 MB or less) without supplying metadata. To perform a simple upload, refer to Perform a simple upload.

  • 因此,要上传文件内容和文件元数据,请使用 uploadType = multipart .

    此外,在您的端点中,使用Drive API v3.但是父母"是指:[{"id":< folderid>"}] 用于Drive API v2.还需要对其进行修改.

    And also, in your endpoint, Drive API v3 is used. But "parents" : [{"id": "<folderid>"}] is for Drive API v2. It is required to also modify it.

    当您的脚本被修改为 uploadType = multipart 时,它如下所示.

    When your script is modified for uploadType=multipart, it becomes as follows.

    使用此脚本时,请设置文件目录,文件名,文件夹id,access_token 的变量.

    When you use this script, please set the variables of filedirectory, filename, folderid, access_token.

    import json
    import requests
    
    filedirectory = '###'
    filename = '###'
    folderid = '###'
    access_token = '###'
    
    metadata = {
        "name": filename,
        "parents": [folderid]
    }
    files = {
        'data': ('metadata', json.dumps(metadata), 'application/json'),
        'file': open(filedirectory, "rb").read()  # or  open(filedirectory, "rb")
    }
    r = requests.post(
        "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
        headers={"Authorization": "Bearer " + access_token},
        files=files
    )
    print(r.text)
    

    注意: