简体   繁体   中英

How to upload all files & sub directory in a directory to sharepoint

I'm writing an automation script to transfer files & subdirectory in a directory to SharePoint from ubuntu. And I'm able to transfer the files from in a directory but failed when uploading the subdirectories.

For reference my code

#importing required packages
import sys
import requests
from requests_ntlm import HttpNtlmAuth
from config import config
import os


#Reading the configuration variables
username=config['sp_user'].split("@")[0]
password=config['sp_password']
sharepoint_url=config['sp_base_path']
sp_folder_url=config['folderUrl']
path=config['path']
domain=config['domain']
domain_username=domain+'\\'+username


#Reading the files from Linux
files = next(os.walk(path))[2]


for i in range(0, len(files)):
    filename = files[i]
    requestUrl = sharepoint_url + '/_api/web/getfolderbyserverrelativeurl(\'' + sp_folder_url + '\')/Files/add(url=\'' + filename + '\',overwrite=true)'
    with open( filename, 'rb') as file_input:
        try:
             headers = {'Content-Type': 'application/json; odata=verbose', 'accept': 'application/json;odata=verbose'}
             r = requests.post(sharepoint_url + "/_api/contextinfo",auth=HttpNtlmAuth(domain_username,password), headers=headers)
             formDigestValue = r.json()['d']['GetContextWebInformation']['FormDigestValue']
             headers = {'Content-Type': 'application/json; odata=verbose', 'accept': 'application/json;odata=verbose', 'x-requestdigest' : formDigestValue}
             uploadResult = requests.post(requestUrl,auth=HttpNtlmAuth(domain_username,'password'), headers=headers, data=file_input.read())


        except Exception as err: 
            print("Some error occurred: " + str(err))    

            

 



May I know what should I need to achieve that and please help me to bridge the gap between my requirement. Could you please try to produce my code. Thanks in advance

UPDATE

I'm getting following error when uploading the files now.

{"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied. You do not have permission to perform this action or access this resource."}}}

The error shows the request has not got authenticated. I suggest you take advantage of below python library for SharePoint:

And there is a similar thread you may take a reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM