[英]create a folder in google drive and uploading files to it
How I can create a folder inside the google drive and upload files into that folder? 如何在Google驱动器中创建一个文件夹并将文件上传到该文件夹? (in python) (在python中)
I have tried with the google tutorials but it is giving me errors 我已经尝试过Google教程,但这给了我错误
creating a folder, not working giving me errors like 'drive_service not defined' 创建文件夹,无法正常工作,给我类似“未定义drive_service”的错误
file_metadata = {
'title': 'Files',
'mimeType': 'application/vnd.google-apps.folder'
}
file = drive_service.files().insert(body=file_metadata,
fields='id').execute()
print 'Folder ID: %s' % file.get('id')
Used this code for uploading a file and it is working, how I can modify it for uploading a file into a folder if that exists, if not create one and upload. 使用此代码来上传文件并且可以正常工作,如何修改该文件以将文件上传到文件夹(如果存在),如果不创建则上传。
import json
import requests
headers = {"Authorization": "Bearer Token"}
para = {
"name": "index.jpeg",
}
files = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': open("./index.jpeg", "rb")
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(r.text)
Here is an example of what I think you're looking for (its a self-contained example, but I think you can modify it to your own existing code): 这是我正在寻找的示例(它是一个独立的示例,但我认为您可以将其修改为自己的现有代码):
from __future__ import print_function
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from httplib2 import Http
from oauth2client import file, client, tools
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/drive.file'
def main():
# Access the Drive service
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))
# Check if folder exists (simply matching by name)
folder_name = "Photos"
folder_id = None
query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='" + folder_name + "'"
results = service.files().list(
pageSize=1, q=query, fields="files(id, name)").execute()
folders = results.get('files', [])
if folders:
folder_id = folders[0]['id']
# If folder not found, then create it.
else:
file_metadata = {
'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder'
}
folder_file = service.files().create(body=file_metadata,
fields='id').execute()
folder_id = folder_file.get('id')
# Add file to folder.
file_metadata = {
'name': 'photo.png',
'parents': [folder_id]
}
media = MediaFileUpload('photo.png',
mimetype='image/png',
resumable=True)
image_file = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
if __name__ == '__main__':
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.