无法使用图形 API 将文件上传到 Sharepoint 网站。找不到资源

Can't upload file to Sharepoint site using Graph API. The resource could not be found

提问人:Diego 提问时间:11/14/2023 最后编辑:Diego 更新时间:11/14/2023 访问量:35

问:

我可以看到驱动器中的文件,但在尝试写入文件时应该不存在。

这是我查找文件的方式:

site_url = https://graph.microsoft.com/v1.0/sites
get_url = f"{site_url}/{site_id}/drives/{drive_id}/root/children"
headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json;odata.metadata=minimal",
    "Accept": "application/json;odata.metadata=minimal"
}
response = requests.get(get_url, headers=headers)
if response.status_code == 200:
    print(response.text)

并得到回应:

{
    "value": [
        {
            "createdDateTime": "2023-11-13T18:21:22Z",
            "lastModifiedDateTime": "2023-11-13T18:21:22Z",
            "name": "Reporte",
            "webUrl": "{site}/Shared%20Documents/Reporte",
        },
        {
            "@microsoft.graph.downloadUrl": "{download_url}",
            "name": "Open pip.txt"
        }
    ]
}

确认我可以访问驱动器, 但是当我尝试编写一个新文件时:

file_name = "Reporte Z.xlsx"
upload_url = f"{site_url}/{site_id}/drives/{drive_id}/root:/{file_name}:/content"

# Set headers
headers = {
    "Authorization": f"Bearer {access_token}",
    "Connection": "Keep-alive",
    "Content-Type": "text/plain"
}

# Read file content
with open(file_path, "rb") as file:
    file_content = file.read()

# Make POST request
response = requests.post(upload_url, headers=headers, data=file_content)

# Check response status
if response.status_code == 201:
    print("File uploaded successfully")
else:
    print("Error uploading file:", response.status_code, response.text)

我收到错误

Error uploading file: 404 {"error":{"code":"itemNotFound","message":"The resource could not be found.","innerError":{"date":"2023-11-13T18:47:51","request-id":"[string]","client-request-id":"[string]"}}}

我尝试删除根目录中的“:”,但获取实体仅允许使用JSON Content-Type标头进行写入。错误

我正在学习本教程(https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http)但无济于事。

我查看了许多线程,但许多线程似乎从未找到解决方案。

sharepoint python-requests microsoft-graph-api

评论


答:

0赞 Diego 11/14/2023 #1

我只需要从 POST 更改为 PUT。即使在教程中也是这么说的。

我会继续这个问题,以防其他人感到困惑。

从:

# Make POST request
response = requests.post(upload_url, headers=headers, data=file_content)

自:

# Make PUT request
response = requests.put(upload_url, headers=headers, data=file_content)

我还将标题更改为:

headers = {
    "Authorization": f"Bearer {access_token}",
    "Accept": "application/json",
    "Content-Type": "text/plain"
}

评论

0赞 jleture 11/14/2023
Microsoft Learn 页面明确指示使用 learn.microsoft.com/en-us/graph/api/...PUT