Reputation: 405
I am able to upload file to Documents
in SharePoint. But I want to upload it to a specific Folder. I am not sure how can I do that. Any help will be welcomed. I am using the code below to upload files.
def upload_file(ctx, listTitle, path):
list_obj = ctx.web.lists.get_by_title(listTitle)
folder = list_obj.root_folder
ctx.load(folder)
ctx.execute_query()
files = folder.files
ctx.load(files)
ctx.execute_query()
with open(path, 'rb') as f:
content = f.read()
file_creation_information = FileCreationInformation()
file_creation_information.overwrite = True
file_creation_information.url = os.path.basename(path)
file_creation_information.content = content
file_new = files.add(file_creation_information)
ctx.load(files)
ctx.execute_query()
upload_file(ctx,'/Documents/reports/',path)
The code above works fine for upload_file(ctx,'Documents',report)
but doesn't work for upload_file(ctx,'Documents/reports',report)
folder. It doesn't work.
Error:
office365.runtime.client_request_exception.ClientRequestException: ('-1, System.ArgumentException', "List 'reports' does not exist at site with URL 'https://sharepoint.com/sites/my_page'.", "404 Client Error: Not Found for url: https://sharepoint.com/sites/my_page/_api/Web/lists/GetByTitle('reports')/RootFolder")
Upvotes: 0
Views: 616
Reputation: 55
The error you're getting is suggesting that you somehow look for a list called reports
. But you want to get a folder-object.
It's not clear which package you're using to connect to sharepoint but the docs say that you need to make an api-call like this:
POST https://{site_url}/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/add(url='a.txt',overwrite=true)
Authorization: "Bearer " + accessToken
Content-Length: {length of request body as integer}
X-RequestDigest: "{form_digest_value}"
"Contents of file"
Uploading a file to the Document directory is working because it's a folder inside the the default directory Shared Documents. You can only access folders inside root with the .root_folder
calls.
Edit 2: As I don't know which package you're using (probably Office365-REST) you can upload a file using the endpoint above in a normal requests.post
-function.
Should look like this:
import requests
url = f'https://{site_url}/_api/web/GetFolderByServerRelativeUrl('{specific Folder URL}')/Files/add(url='a.txt',overwrite=true)'
headers = {Authorization: "Bearer " + accessToken,
Content-Length: content-length
}
payload = your_byte_string
response = requests.post(url = url, headers=headers, data = payload}
Upvotes: 1