我尝试使用 python 代码将文件上传到一个驱动器:
请参考以下我的上传脚本:
url = f'https://graph.microsoft.com/v1.0/users/{user_id}/drive/root:/{local_file_path}:/createUploadSession'
headers = {
'Authorization': 'Bearer {}'.format(access_token),
'Content-Type': 'application/json'
}
session_data = {
"item": {
"@microsoft.graph.conflictBehavior": "replace", # Action on conflict (replace, fail, etc.)
"name": "2.txt" # The file name in OneDrive
}
}
upload_session = requests.post(url=url, headers=headers,json=session_data).json()
错误信息:
{"error": {"code": "Request_BadRequest", "message": "Specified HTTP method is not allowed for the request target.",
"innerError": {"date": "2024-11-07T04:21:05", "request-id": "7be5355c-381a-4ea8-9d89-0b0a99208bb4", "client-request-id":
"7be5355c-381a-4ea8-9d89-0b0a99208bb4"}}}
正确的 URL 结构应为 https://graph.microsoft.com/v1.0/users/{user_id}/drive/root:/{file_name}:/createUploadSession,其中:
{user_id} 是您的 OneDrive 用户 ID。 {file_name} 是您要上传的文件的名称。 授权标头:确保 access_token 有效并具有所需的权限(例如 OneDrive 的 Files.ReadWrite 范围) 试试这个,可能会有所帮助
import requests
# Variables
user_id = 'your_user_id'
access_token = 'your_access_token'
file_name = '2.txt' # Replace with your file's name
local_file_path = f'/drive/root:/{file_name}:/createUploadSession'
# URL and headers
url = f'https://graph.microsoft.com/v1.0/users/{user_id}{local_file_path}'
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
# JSON data for session
session_data = {
"item": {
"@microsoft.graph.conflictBehavior": "replace", # Action on conflict
"name": file_name # Name to be used in OneDrive
}
}
# Create upload session
response = requests.post(url=url, headers=headers, json=session_data)
# Check for errors
if response.status_code == 200:
upload_session = response.json()
print("Upload session created:", upload_session)
else:
print("Error:", response.json())