这个错误通常是因为OneDrive API无法找到指定的文件夹路径,造成上传失败。为了解决这个问题,我们需要确认文件夹是否存在,并在代码中正确指定文件夹路径。
以下是一个示例代码来保存附件到OneDrive的指定文件夹中:
import onedrive_sdk
import uuid
import os
# 首先设置API凭证和文件夹路径
client_id = 'your_client_id'
client_secret = 'your_client_secret'
scopes = ['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
folder_name = 'test_folder'
# 然后进行身份验证
client = onedrive_sdk.get_default_client(client_id=client_id, scopes=scopes)
url = client.auth_provider.get_auth_url()
code = input('Paste the authentication code here: ')
client.auth_provider.authenticate(code)
# 获取根目录和指定文件夹路径
root_folder = client.item(drive='me', id='root').get()
folder_path = '/{}/{}'.format(root_folder['name'], folder_name)
items = client.item(drive='me', path=folder_path + ':/children').get()
# 检查文件夹是否存在,如果不存在则创建
if not items.get('value'):
item = onedrive_sdk.Item()
item.name = folder_name
item.folder = onedrive_sdk.Folder()
folder = client.item(drive='me', path=root_folder['name']).children.add(item)
folder_path = folder['parentReference']['path'] + '/' + folder_name
# 为要上传的文件创建一个唯一的文件名
filename = str(uuid.uuid4())
_, file_extension = os.path.splitext(attachment.filename)
filename += file_extension
# 上传文件到指定文件夹中
with attachment.open() as f:
client.item(drive='me', path=folder_path + '/' + filename).upload(f)
print('Attachment saved to OneDrive')
在上面的代码中,我们首先设置了API凭证和文件夹路径。然后进行身份验证
上一篇:保存附件 IMAP 和 PHP
下一篇:保存附件导致内存错误