pythonsharepointsharepoint-apisharepointdocumentlibraryoffice365-rest-client

Upload file to a subfolder in Sharepoint with office365 API


I am trying to upload a file to sharepoint folder. I got the following code working that just uploads the files to the root documents directory. But I want it to upload to a specific directory in the sharepoint.

Variables:

fullurl = 'https://xxxx.sharepoint.com/sites/yyyy/'
fileName = 'report.xlsx'
rootfolder = 'Documents'
targetfolder = '/00 First/01 Second/03 Third/'

So, the target location for file upload is Documents/00 First/01 Second/03 Third/.

Working code that uploads file to root documents folder.

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()

I tried to change the code to upload the file to the subfolder as given in 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()

But this fails and ends up with

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:

Solution

  • It seems that the folder path you set in the code is not correct. For example, I have a SPO site (https://abc.sharepoint.com/sites/s01) and the site has a default library (Shared Documents), then i want to upload file to "FolderA" in this library.

    The corresponding path should be:

    "/sites/s01/Shared Documents/FolderA"
    

    BR