Office365-REST-Python-Client icon indicating copy to clipboard operation
Office365-REST-Python-Client copied to clipboard

Cannot understand how to upload file to subfolder

Open LucaPaganin opened this issue 3 years ago • 1 comments

I am trying to upload a file to a subfolder of the root folder of our sharepoint site.

The following is the source code I am trying to use to upload the file

import os
from office365.sharepoint.client_context import ClientContext
from pathlib import Path
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential

username = "***"
password = "***"
url = "https://***.sharepoint.com/sites/***"

ctx = ClientContext(url).with_credentials(UserCredential(username, password))


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


remotedst = "sites/Testing Environment/Shared Documents/cypressTests"
folder = ctx.web.get_folder_by_server_relative_url(remotedst)
folder.upload_file("test.txt", file_content).execute_query()

But I am continuously getting this 401 error image

With version 2.3.11 I was able to upload a file by using the following code

from office365.sharepoint.files.file_creation_information import FileCreationInformation

def uploadSingleFile(ctx, folder, dstname, srcpath, overwrite=True):
    t0 = time.time()
    info = FileCreationInformation()
    info.url = dstname
    info.overwrite = overwrite
    with open(srcpath, 'rb') as fh:
        info.content = fh.read()
    target_file = folder.files.add(info)
    ctx.execute_query()
    print(f"Elapsed time {time.time()-t0:6f} s")

source = Path("/path/to/local/file")
remoteFolder = ctx.web.get_folder_by_server_relative_url("/Shared Documents/cypressTests")
uploadSingleFile(ctx, remoteFolder, source.name, source)

Can you help me?

LucaPaganin avatar Jun 28 '22 14:06 LucaPaganin

The following works just fine for me:

where: self.tenant + site_url = 'https://xxxx.sharepoint.com/sites/xxxx' destination = 'Shared Documents/test_folder/test1.csv'


self.ctx = ClientContext(self.tenant + site_url).with_credentials(
            UserCredential(self.sharepoint_user, self.sharepoint_user_pwd)
        )

.....
....
    
def upload_file(self, source_file, destination):
        """
        Uploads a specific file to sharepoint

        :param source_file: Path to the local file to be uploaded
        :type source_file: str
        :param destination: Relative location in sharepoint where the file should be uploaded to
        :type destination: str
        :return: web url for sharepoint of the file uploaded
        :rtype: str
        """

        with open(source_file, "rb") as content_file:
            file_content = content_file.read()

        directory, file_name = os.path.split(destination)

        logger.info(f"Uploading file {file_name} to {directory}")

        # creates folder if missing in Sharepoint
        self.ctx.web.ensure_folder_path(directory).execute_query()

        file = (
            self.ctx.web.get_folder_by_server_relative_url(directory)
            .upload_file(file_name, file_content)
            .execute_query()
        )

        logger.info(f"[Ok] File {file_name} has been uploaded to {directory}")
        sharepoint_file_url = f"{self.tenant}{self.site}/{directory}/{file_name}"
        return sharepoint_file_url 

nmduarte avatar Jul 16 '22 22:07 nmduarte

Closing this one since considered resolved

vgrem avatar Feb 20 '24 21:02 vgrem