【发布时间】:2020-11-10 21:57:22
【问题描述】:
我正在尝试将文件上传到 sharepoint 文件夹。我得到了以下代码,它只是将文件上传到根documents 目录。但我希望它上传到共享点中的特定目录。
变量:
fullurl = 'https://xxxx.sharepoint.com/sites/yyyy/'
fileName = 'report.xlsx'
rootfolder = 'Documents'
targetfolder = '/00 First/01 Second/03 Third/'
所以,文件上传的目标位置是Documents/00 First/01 Second/03 Third/。
将文件上传到根documents 文件夹的工作代码。
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file_creation_information import FileCreationInformation
ctx_auth = AuthenticationContext(url=fullurl)
if ctx_auth.acquire_token_for_user(username=username,
password=password):
ctx = ClientContext(fullurl, ctx_auth)
target_list = ctx.web.lists.get_by_title(rootfolder)
info = FileCreationInformation()
with open(fileName, 'rb') as content_file:
info.content = content = content_file.read()
info.url = fileName
info.overwrite = True
upload_file = target_list.rootFolder.files.add(info)
ctx.execute_query()
我尝试更改代码以将文件上传到targefolder 中给出的子文件夹。
ctx_auth = AuthenticationContext(url=fullurl)
if ctx_auth.acquire_token_for_user(username=username,
password=password):
ctx = ClientContext(fullurl, ctx_auth)
libraryRoot = ctx.web.get_folder_by_server_relative_url(targetfolder)
info = FileCreationInformation()
with open(fileName, 'rb') as content_file:
info.content = content = content_file.read()
info.url = fileName
info.overwrite = True
upload_file = libraryRoot.files.add(info)
ctx.execute_query()
但这失败了,结果是
HTTPError: 400 Client Error: Bad Request for url: https://xxxx.sharepoint.com/sites/yyyy/_api/Web/getFolderByServerRelativeUrl('....')/Files/add(overwrite=true,url='report.xlsx')
ClientRequestException: ('-2147024809, System.ArgumentException', 'Server relative urls must start with SPWeb.ServerRelativeUrl', "400 Client Error: Bad Request for url:
【问题讨论】:
标签: python sharepoint sharepoint-api sharepointdocumentlibrary office365-rest-client