如何将文件上传到SharePoint文件夹

发布于 2025-02-08 05:20:31 字数 2697 浏览 0 评论 0原文

我想使用Office365-rest-python-client库将文件从本地计算机上传到SharePoint。我必须将文件上传到SharePoint中的特定文件夹。文档似乎无处不在。 GitHub存储库提供了以下解决方案,将文件上传到主要的“文档” SP文件夹,但是如果我的子文件夹像“ Document”/“ Documents/Folder1”,该怎么办?

这是将文件上传到SharePoint中的文档的代码:

import os

from office365.sharepoint.client_context import ClientContext
from tests import test_user_credentials, test_team_site_url

ctx = ClientContext(test_team_site_url).with_credentials(test_user_credentials)

path = "test_file.txt"
with open(path, 'rb') as content_file:
    file_content = content_file.read()

list_title = "Documents"
target_folder = ctx.web.lists.get_by_title(list_title).root_folder
name = os.path.basename(path)
target_file = target_folder.upload_file(name, file_content).execute_query()
print("File has been uploaded to url: {0}".format(target_file.serverRelativeUrl))

我尝试将list_title变量更改为“ document/folder1”,但作为结果获取以下错误消息:

Traceback (most recent call last):
  File "/Users/a/venv/lib/python3.9/site-packages/office365/runtime/client_request.py", line 80, in execute_query
    response.raise_for_status()
  File "/Users/a/venv/lib/python3.9/site-packages/requests/models.py", line 953, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://company.sharepoint.com/sites/companySite/_api/Web/lists/GetByTitle('Documents%2FFolder1')/RootFolder/Files/add(overwrite=true,url='test_file.txt')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/example.py", line 27, in <module>
    target_file = target_folder.upload_file(name, file_content).execute_query()
  File "/Users/a/venv/lib/python3.9/site-packages/office365/runtime/client_object.py", line 41, in execute_query
    self.context.execute_query()
  File "/Users/a/venv/lib/python3.9/site-packages/office365/runtime/client_runtime_context.py", line 139, in execute_query
    self.pending_request().execute_query()
  File "/Users/a/venv/lib/python3.9/site-packages/office365/runtime/client_request.py", line 84, in execute_query
    raise ClientRequestException(*e.args, response=e.response)
office365.runtime.client_request_exception.ClientRequestException: ('-1, System.ArgumentException', "List 'Documents/Folder1' does not exist at site with URL 'https://company.sharepoint.com/sites/companySite'.", "404 Client Error: Not Found for url: https://company.sharepoint.com/sites/companySite/_api/Web/lists/GetByTitle('Documents%2FFolder1')/RootFolder/Files/add(overwrite=true,url='test_file.txt')")

I want to upload a file from my local machine to SharePoint using the Office365-REST-Python-Client library. The issue I'm having to uploading the file to a specific folder in SharePoint. Documentation seems to be all over the place. The Github repo provides the following solution to upload a file to the main "Documents" SP folder but what if I had subfolders like "Documents/Folder1"?

Here's the code to upload file to Documents in SharePoint:

import os

from office365.sharepoint.client_context import ClientContext
from tests import test_user_credentials, test_team_site_url

ctx = ClientContext(test_team_site_url).with_credentials(test_user_credentials)

path = "test_file.txt"
with open(path, 'rb') as content_file:
    file_content = content_file.read()

list_title = "Documents"
target_folder = ctx.web.lists.get_by_title(list_title).root_folder
name = os.path.basename(path)
target_file = target_folder.upload_file(name, file_content).execute_query()
print("File has been uploaded to url: {0}".format(target_file.serverRelativeUrl))

I tried to change the list_title variable to "Documents/Folder1" but get the following error message as a result:

Traceback (most recent call last):
  File "/Users/a/venv/lib/python3.9/site-packages/office365/runtime/client_request.py", line 80, in execute_query
    response.raise_for_status()
  File "/Users/a/venv/lib/python3.9/site-packages/requests/models.py", line 953, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://company.sharepoint.com/sites/companySite/_api/Web/lists/GetByTitle('Documents%2FFolder1')/RootFolder/Files/add(overwrite=true,url='test_file.txt')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/example.py", line 27, in <module>
    target_file = target_folder.upload_file(name, file_content).execute_query()
  File "/Users/a/venv/lib/python3.9/site-packages/office365/runtime/client_object.py", line 41, in execute_query
    self.context.execute_query()
  File "/Users/a/venv/lib/python3.9/site-packages/office365/runtime/client_runtime_context.py", line 139, in execute_query
    self.pending_request().execute_query()
  File "/Users/a/venv/lib/python3.9/site-packages/office365/runtime/client_request.py", line 84, in execute_query
    raise ClientRequestException(*e.args, response=e.response)
office365.runtime.client_request_exception.ClientRequestException: ('-1, System.ArgumentException', "List 'Documents/Folder1' does not exist at site with URL 'https://company.sharepoint.com/sites/companySite'.", "404 Client Error: Not Found for url: https://company.sharepoint.com/sites/companySite/_api/Web/lists/GetByTitle('Documents%2FFolder1')/RootFolder/Files/add(overwrite=true,url='test_file.txt')")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌无敌 2025-02-15 05:20:31

当我寻找完全相同的答案时,我发现了您的问题,并得出了有关文档需要更有帮助的同样结论。

我使用的是Azure Service主体(注册应用程序)而不是用户名/密码,这是主要区别。

我使用Keyring将信用固定在Windows凭据管理器中。

因此,如果您还没有弄清楚,那么对于任何发现您的问题的人来说,这里的代码对我有用;

scriptName ='send_csv_to_spo.py'
import keyring #to access Windows Credentials Manager, where user/passwords are stored securely
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.client_credential import ClientCredential
import os #interact with OS for file actions
#Get creds from Windows Credentials Manager
appID = 'AppName' #Azure Registered App
clientId = '********-****-****-****-*************'
secret=keyring.get_password(appID,clientId)
sharepoint_url = f'https://*******.sharepoint.com'
siteName = f'/sites/*******'
target_url = f"folder/sub-folder"
site_url = sharepoint_url + siteName
#ensure file to send is in the same folder as this script
#call function from other script, passing the fileName
#eg:
#import send_csv_to_spo as sendFile #imports this file as module
#fileStr = 'test.csv' #test file in same folder
#sendFile.sendFileToSPO(fileStr) #calls function in module

def sendFileToSPO(fileName):
    #Authenticate using stored Azure App credentials
    from office365.sharepoint.client_context import ClientContext
    ctx = ClientContext(site_url).with_credentials(ClientCredential(clientId, secret))
    #Collect file for uploading
    with open(fileName, 'rb') as content_file:
        file_content = content_file.read()
    #Upload file to target url
    target_folder = ctx.web.get_folder_by_server_relative_url(target_url)
    name = os.path.basename(fileName)
    target_file = target_folder.upload_file(name, file_content).execute_query()
    print("File has been uploaded as follows: {0}".format(target_file.serverRelativeUrl))
    #File has been uploaded to url: /sites/******/******/******/testPush.csv

I found your question while I was looking for the exact same answer and having come to the same conclusions about the documentation needing to be a little more helpful.

I'm using an Azure Service Principal (Registered App) not username/password, that's the primary difference.

I store creds securely in Windows Credentials Manager using keyring.

So, in case you didn't figure it out yet, and for anyone else who finds your question, here's code that worked for me;

scriptName ='send_csv_to_spo.py'
import keyring #to access Windows Credentials Manager, where user/passwords are stored securely
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.client_credential import ClientCredential
import os #interact with OS for file actions
#Get creds from Windows Credentials Manager
appID = 'AppName' #Azure Registered App
clientId = '********-****-****-****-*************'
secret=keyring.get_password(appID,clientId)
sharepoint_url = f'https://*******.sharepoint.com'
siteName = f'/sites/*******'
target_url = f"folder/sub-folder"
site_url = sharepoint_url + siteName
#ensure file to send is in the same folder as this script
#call function from other script, passing the fileName
#eg:
#import send_csv_to_spo as sendFile #imports this file as module
#fileStr = 'test.csv' #test file in same folder
#sendFile.sendFileToSPO(fileStr) #calls function in module

def sendFileToSPO(fileName):
    #Authenticate using stored Azure App credentials
    from office365.sharepoint.client_context import ClientContext
    ctx = ClientContext(site_url).with_credentials(ClientCredential(clientId, secret))
    #Collect file for uploading
    with open(fileName, 'rb') as content_file:
        file_content = content_file.read()
    #Upload file to target url
    target_folder = ctx.web.get_folder_by_server_relative_url(target_url)
    name = os.path.basename(fileName)
    target_file = target_folder.upload_file(name, file_content).execute_query()
    print("File has been uploaded as follows: {0}".format(target_file.serverRelativeUrl))
    #File has been uploaded to url: /sites/******/******/******/testPush.csv
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文