簡體   English   中英

如何使用 Google Drive API 和 Python 將文件上傳到特定文件夾?

[英]How to upload file into specific folder with Google Drive API and Python?

我正在將 jpg 文件上傳到我的谷歌驅動器帳戶。 它工作正常,但我需要將它上傳到特定文件夾,但不確定如何在元數據中設置 parents 參數。

這是我的代碼:

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 Drive 中的特定文件夾。
  • 您想使用 python 的requests來實現此目的。

修改點:

  • uploadType=media的情況下,官方文檔是這樣說的。

    簡單上傳(uploadType=media)。 使用此上傳類型可快速傳輸小型媒體文件(5 MB 或更少),而無需提供元數據。 要執行簡單上傳,請參閱執行簡單上傳。

  • 所以為了上傳文件內容和文件元數據,請使用uploadType=multipart

  • 此外,在您的端點中,使用了 Drive API v3。 但是"parents": [{"id": "<folderid>"}]適用於 Drive API v2。 還需要對其進行修改。

當您的腳本被修改為uploadType=multipart時,它變成如下。

修改后的腳本:

使用此腳本時,請設置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)

筆記:

  • 此修改后的腳本假定您的訪問令牌可用於將文件上傳到 Google Drive。

參考:

看來我已經能夠用這個代碼讓 Javascript SDK 做出反應

                                gapi.client.drive.files.create({
                                    name: 'multapart.jpg',   //OPTIONAL
                                    uploadType: 'multipart',
                                },{body:'your content here',content:'your content here'})

其中 media 是圖像的字節表示

在此處輸入圖像描述

在chronium edge它抱怨說

在 'https://content.googleapis.com/drive/v3/files?name=resumable.jpg&body=%EF%BF%BD%EF%....%BD&uploadType=multipart&alt=json&key=[你不能訪問 XMLHttpRequest看到這個哈哈]'來自原點'https://content.googleapis.com'已被 CORS 政策阻止:跨源請求僅支持協議方案:http、數據、chrome-extension、edge、Z5E056C500A1C47BADE517 .

在邊緣遺產中,它說它格式錯誤,當我上傳類型=媒體時,它說是使用https://content.googleapis.com/drive/v3/files而不是https://content.googleapis.com/upload /drive/v3/files , so the JS SDK is unreliable and riddled with bugs, glad I got it to react, if only someone can find the logic to give it the right URL because I believe the js SDK is not buggy, google doesnt想讓人們使用它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM