Ich versuche, eine Datei auf Sharepoint hochzuladen. Bin ich auf dem richtigen Weg?
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
with open(path, 'rb') as f:
content = f.read()
file_creation_information = FileCreationInformation()
file_creation_information.overwrite = True
file_creation_information.url = path
file_creation_information.content = content
file_new = files.add(file_creation_information)
Ich habe nur die ClientRequest class
, um dies zu tun.
def upload_binary_file(self, file):
"""Attempt to upload a binary file to SharePoint"""
folder_url = "folder_to_upload_to"
text_file = basename(file.name)
full_url = "{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/add(url='{2}', overwrite=true)".format(self.base_url, folder_url, text_file)
options = RequestOptions(full_url)
context = ClientContext(full_url, self.ctx_auth)
options.set_header('Accept', 'application/json; odata=verbose')
options.set_header('Content-Type', 'application/octet-stream')
options.set_header('Content-Length', str(os.path.getsize(file.name)))
options.set_header('X-RequestDigest', YOUR_FORM_DIGEST)
options.method = 'POST'
file_name = file.name
with open(file_name, 'rb') as outfile:
# instead of executing the query directly, we'll try to go around
# and set the json data explicitly
context.authenticate_request(options)
data = requests.post(url=full_url, data=outfile, headers=options.headers, auth=options.auth)
if data.status_code == 200:
# our file has uploaded successfully
# let's return the URL
base_site = data.json()['d']['Properties']['__deferred']['uri'].split("/sites")[0]
relative_url = data.json()['d']['ServerRelativeUrl'].replace(' ', '%20')
return base_site + relative_url
else:
return "Log Failed to Upload"
@benpolinsky Danke, dass gepostet hast , die ich irgendwann zum
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.runtime.utilities.request_options import RequestOptions
from office365.sharepoint.file_creation_information import FileCreationInformation
from settings import settings
import requests
import os
from os.path import basename
ctx_auth = AuthenticationContext(url=settings['url'])
if ctx_auth.acquire_token_for_user(username=settings['username'], password=settings['password']):
upload_binary_file("c:\temp\myfile.txt",ctx_auth)
def upload_binary_file(file_path, ctx_auth):
"""Attempt to upload a binary file to SharePoint"""
base_url = settings['url']
folder_url = "MyFolder"
file_name = basename(file_path)
files_url ="{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/add(url='{2}', overwrite=true)"
full_url = files_url.format(base_url, folder_url, file_name)
options = RequestOptions(settings['url'])
context = ClientContext(settings['url'], ctx_auth)
context.request_form_digest()
options.set_header('Accept', 'application/json; odata=verbose')
options.set_header('Content-Type', 'application/octet-stream')
options.set_header('Content-Length', str(os.path.getsize(file_path)))
options.set_header('X-RequestDigest', context.contextWebInformation.form_digest_value)
options.method = 'POST'
with open(file_path, 'rb') as outfile:
# instead of executing the query directly, we'll try to go around
# and set the json data explicitly
context.authenticate_request(options)
data = requests.post(url=full_url, data=outfile, headers=options.headers, auth=options.auth)
if data.status_code == 200:
# our file has uploaded successfully
# let's return the URL
base_site = data.json()['d']['Properties']['__deferred']['uri'].split("/sites")[0]
relative_url = data.json()['d']['ServerRelativeUrl'].replace(' ', '%20')
return base_site + relative_url
else:
return data.json()['error']
Ich würde es vorziehen, eine einfache API zu haben, um eine Datei auf Sharepoint hochzuladen. Das ist viel zu komplex.
@attibalazs Danke für das Skript. Ich bin auf folgenden Fehler gestoßen und stecke derzeit hier fest:
Datei "C: \ Python27 \ lib \ site-packages \ office365 \ runtime \ auth \ saml_token_provider.py", Zeile 65, in get_authentication_cookie
return 'FedAuth =' + self.FedAuth + '; rtFa = '+ self.rtFa
TypeError: Objekte 'str' und 'NoneType' können nicht verkettet werden
Mussten Sie neben der SP Online-URL, dem Benutzernamen und dem Kennwort auch eine Client-ID und ein Client-Geheimnis verwenden?
Danke für dieses @attibalazs . Es hat super für mich funktioniert.
Ich habe Zweifel. Funktioniert dieser Code für Organisationskonten wie [email protected] oder benötigen wir ein ordnungsgemäßes office365-Konto wie [email protected] ?
Hallo, ich habe das @attibalazs- Skript verwendet, das anscheinend gut funktioniert, bis ich versuche, Daten in Sharepoint hochzuladen:
data = requests.post(url=full_url, data=outfile, headers=options.headers, auth=options.auth)
Ich habe den Status 403. Gibt es etwas, das ich in meiner Bürokontokonfiguration ändern sollte, um auf diese Weise Schreibrechte in Sharepoint zu erhalten?
@attibalazs
API verwenden. status = ctx_auth.acquire_token_for_app () anstelle von status = ctx_auth.acquire_token_for_user (Benutzername, Passwort)
und installieren Sie das Paket. pip install -U certifi
Hallo, ich habe einige Anpassungen an Ihrem Code hinzugefügt, die für mich funktionieren:
Ich versuche, eine Datei auf Sharepoint hochzuladen. Bin ich auf dem richtigen Weg?
`` `
def upload_file (ctx, listTitle, path):
list_obj = ctx.web.lists.get_by_title (listTitle)
folder = list_obj.root_folder
ctx.load (Ordner)
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()
Schöne Grüße,
Ich schlage vor, dieses zu schließen, da es beantwortet wurde.
Die empfohlene Methode zum Hochladen einer Datei in die SharePoint-Bibliothek wird nachfolgend gezeigt:
#read a local file
path = "../tests/data/SharePoint User Guide.docx"
with open(path, 'rb') as content_file:
file_content = content_file.read()
#upload it into Documents library
target_folder = context.web.lists.get_by_title("Documents").rootFolder
info = FileCreationInformation()
info.content = file_content
info.url = os.path.basename(path)
info.overwrite = True
target_file = target_folder.files.add(info)
context.execute_query()
Aber wenn Datei größer als 2 MB dann braucht Datei als Menge von Datenblöcken hochgeladen werden:
ctx = ClientContext(site_url, ctx_auth)
size_1Mb = 1000000
local_path = "./data/big_buck_bunny.mp4"
target_url = "/Shared Documents"
result_file = ctx.web.get_folder_by_server_relative_url(target_url).files.create_upload_session(local_path, size_1Mb, print_upload_progress)
ctx.execute_query()
print('File {0} has been uploaded successfully'.format(result_file.properties['ServerRelativeUrl']))
wo
def print_upload_progress(offset):
print("Uploaded '{0}' bytes...".format(offset))
Wenn Sie es vorziehen, eine Upload-Anfrage selbst zu erstellen, sind die von @attibalazs und @benpolinsky bereitgestellten Snippets ein guter Weg.
Vadim
Hilfreichster Kommentar
@benpolinsky Danke, dass gepostet hast , die ich irgendwann zum