我正在尝试将文件上传到共享点,我在正确的路径上吗?
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)
我只用ClientRequest class
来做到这一点。
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感谢您发布摘要,最终我使它起作用了。 起初我很难获取表格摘要,但是一旦我弄清楚了如何做到这一点就可以了。
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']
我希望有一个简单的api将文件上传到sharepoint。 这太复杂了。
@attibalazs感谢您的脚本。 我确实遇到了以下错误,目前停留在这里:
get_authentication_cookie中的第65行的文件“ C:\ Python27 \ lib \ site-packages \ office365 \ runtime \ auth \ saml_token_provider.py”
返回'FedAuth ='+ self.FedAuth +'; rtFa ='+ self.rtFa
TypeError:无法连接“ str”和“ NoneType”对象
除了SP Online URL,用户名和密码之外,您还需要使用客户端ID和客户端密钥吗?
感谢您的@attibalazs 。 这对我来说很棒。
我怀疑..没有了组织此代码的工作占像[email protected]或者我们需要有一个适当的office365帐户像[email protected] ?
嗨,我使用了@attibalazs脚本,在我尝试在Sharepoint中上传数据之前,该脚本似乎运行良好:
data = requests.post(url=full_url, data=outfile, headers=options.headers, auth=options.auth)
我的状态为403。 我应该在我的办公室帐户配置中进行一些更改以获取以这种方式在Sharepoint中进行写入的权利吗?
@attibalazs
使用API。 status = ctx_auth.acquire_token_for_app(),而不是status = ctx_auth.acquire_token_for_user(用户名,密码)
并安装packge。 点安装-U认证
您好,我为您的代码添加了一些对我有用的调整:
我正在尝试将文件上传到共享点,我在正确的路径上吗?
```
def upload_file(ctx,listTitle,path):
list_obj = ctx.web.lists.get_by_title(listTitle)
文件夹= list_obj.root_folder
ctx.load(文件夹)
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()
问候,
由于已解决该问题,因此我建议将其关闭。
下面演示了将文件上传到SharePoint库的推荐方法:
#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()
但是,如果文件大于2 MB,则需要将文件作为一组块上载:
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']))
在哪里
def print_upload_progress(offset):
print("Uploaded '{0}' bytes...".format(offset))
如果您喜欢自己构建上传请求,那么@attibalazs和@benpolinsky提供的不错的选择。
瓦迪姆
最有用的评论
@benpolinsky感谢您发布摘要,最终我使它起作用了。 起初我很难获取表格摘要,但是一旦我弄清楚了如何做到这一点就可以了。