繁体   English   中英

Python:如何使用 folderId 将文件上传到 Google Drive 中的特定文件夹

[英]Python: How to upload files to a specific folder in Google Drive using folderId

所以我正在尝试将文件上传到用户指定的特定 Google Drive 文件夹。 下面是我试过的代码。 我得到了 folderID 并尝试将文件发布到该文件夹​​,但是我收到404 Not Found错误。

def post_file(self, files_to_send, config = {}):
  if config:
    if type(config) is str:
      config = literal_eval(config)
    path_id = config.get('path')
  for file_to_send in files_to_send:
    filename = file_to_send.name.split('/')[-1]
    status = self.call.post('https://www.googleapis.com/upload/drive/v2/files?uploadType=media/' + str(path_id) + "/children")

使用 Drive API 文档中的接口,我能够使用相同的文件夹 ID 获取数据,但我无法发布(即使使用接口)。 Files_to_send是一个包含我需要上传到特定文件夹的所有文件的列表, config包含文件夹路径。

我需要帮助了解我做错了什么。 我已经阅读了文档并查看了其他答案,但我还没有找到解决方案。 当我不指定文件夹 ID 时,一个虚拟文件确实会发布到我的驱动器,但它不会上传我想要的文件,并且当我指定文件夹 ID 时它根本不会上传任何内容。

本质上,我需要帮助插入一个文件,该文件进入 Google Drive 中的特定文件夹。

谢谢!

我相信你应该发送一个包含parents提交的元数据 JSON。 就像是:

{
    "parents" : [path_id]
}

您可以在此处尝试此 API: https : //developers.google.com/drive/v2/reference/files/insert

解决这个问题需要两个步骤:

  1. 获取文件夹 ID:

     folder_list = self.drive.ListFile({'q': "trashed=false"}).GetList() for folder in folder_list: print 'folder title: %s, id: %s' % (folder['title'], folder['id'])
  2. 找到所需文件夹的 ID 后,使用此功能:

     def upload_file_to_specific_folder(self, folder_id, file_name): file_metadata = {'title': file_name, "parents": [{"id": folder_id, "kind": "drive#childList"}]} folder = self.drive.CreateFile(file_metadata) folder.SetContentFile(file_name) #The contents of the file folder.Upload()

在 v3 中只需更新 file_metadata :

file_metadata = {'name': 'exmample_file.pdf', "parents": ["ID_OF_THE_FOLDER"]}

我实现将文件放入特定文件夹的方法是在元数据中传递以下信息。

这里<someFolderID>信息可以检索为: 1. 转到谷歌驱动器 2. 选择文件夹 3. 观察地址栏,它会在https://drive.google.com/drive/folders/之后有一些值

{
"parents":[
"id": "<someFolderID>",
"kind": "drive#file"
]
}

对于具体样品

...
from googleapiclient import discovery
from apiclient.http import MediaFileUpload
...
drive_service = discovery.build('drive', 'v3', credentials=creds)
...
def uploadFile(filename, filepath, mimetype, folderid):
    file_metadata = {'name': filename,
                     "parents": [folderid]
                     }
    media = MediaFileUpload(filepath,
                            mimetype=mimetype)
    file = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id').execute()
    print('File ID: %s' % file.get('id'))
  
#sample to use it:
filename = 'cible.png'
filepath = 'path/to/your/cible.png'
mimetype = 'image/png'
folderid = 'your folder id' #ex:'1tQ63546ñlkmulSaZtz5yeU5YTSFMRRnJz'
uploadFile(filename, filepath, mimetype, folderid)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM