如何通过API或PowerShell实现本地文件自动上传至SharePoint 2019本地版文档库
针对你的需求,完全可以通过PowerShell脚本或**SharePoint API(CSOM/REST)**实现本地文件夹到文档库的自动上传,以下是具体实现方案:
一、PowerShell方案(基于CSOM)
该方案利用SharePoint Client Side Object Model(CSOM)实现批量上传,支持递归处理子文件夹,适合快速自动化场景。
实现脚本
# 加载SharePoint CSOM程序集(路径对应SharePoint 2019安装目录) Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" # 配置参数 $siteUrl = "http://你的SharePoint站点URL" $libraryName = "目标文档库名称" $localFolderPath = "C:\folder" $username = "域账号(格式:domain\username)" $password = ConvertTo-SecureString "你的密码" -AsPlainText -Force $credential = New-Object System.Net.NetworkCredential($username, $password) # 创建客户端上下文 $context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) $context.Credentials = $credential # 获取目标文档库 $library = $context.Web.Lists.GetByTitle($libraryName) $context.Load($library) $context.ExecuteQuery() # 递归上传文件及子文件夹函数 function Upload-FileToSP { param( [string]$localPath, [Microsoft.SharePoint.Client.Folder]$spFolder ) $items = Get-ChildItem -Path $localPath foreach ($item in $items) { if ($item.PSIsContainer) { # 在SharePoint创建对应子文件夹 $newSpFolder = $spFolder.Folders.Add($item.Name) $context.Load($newSpFolder) $context.ExecuteQuery() # 递归处理子文件夹内容 Upload-FileToSP -localPath $item.FullName -spFolder $newSpFolder } else { # 读取本地文件内容并上传 $fileContent = [System.IO.File]::ReadAllBytes($item.FullName) $fileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation $fileCreationInfo.Content = $fileContent $fileCreationInfo.Url = $item.Name $fileCreationInfo.Overwrite = $true # 覆盖已存在文件 $uploadedFile = $spFolder.Files.Add($fileCreationInfo) $context.Load($uploadedFile) $context.ExecuteQuery() Write-Host "已完成上传: $($item.FullName) -> $($spFolder.ServerRelativeUrl)/$($item.Name)" } } } # 启动上传 $rootFolder = $library.RootFolder Upload-FileToSP -localPath $localFolderPath -spFolder $rootFolder Write-Host "所有文件上传完成"
注意事项
- 确保CSOM程序集路径正确(
16对应SharePoint 2019,若为2016则是15) - 执行脚本的账号需具备目标文档库的编辑权限
- 若上传大文件(超过2GB),需改用
File.SaveBinaryDirect方法实现分片上传
二、API方案(CSOM C#/REST)
1. CSOM C#实现
适合集成到自定义应用程序中,逻辑与PowerShell一致,支持更复杂的业务扩展。
using Microsoft.SharePoint.Client; using System; using System.IO; namespace SharePointUploader { class Program { static void Main(string[] args) { string siteUrl = "http://你的SharePoint站点URL"; string libraryName = "目标文档库名称"; string localFolderPath = @"C:\folder"; string username = "domain\\username"; string password = "你的密码"; using (ClientContext context = new ClientContext(siteUrl)) { // 配置身份验证 context.Credentials = new System.Net.NetworkCredential(username, password); // 获取文档库根文件夹 List targetLibrary = context.Web.Lists.GetByTitle(libraryName); context.Load(targetLibrary.RootFolder); context.ExecuteQuery(); // 递归上传文件夹内容 UploadFolderContents(localFolderPath, targetLibrary.RootFolder, context); Console.WriteLine("文件上传完成"); Console.ReadLine(); } } static void UploadFolderContents(string localFolderPath, Folder spFolder, ClientContext context) { DirectoryInfo dirInfo = new DirectoryInfo(localFolderPath); // 上传当前文件夹下所有文件 foreach (FileInfo fileInfo in dirInfo.GetFiles()) { using (FileStream fs = fileInfo.OpenRead()) { FileCreationInformation fileCreationInfo = new FileCreationInformation { ContentStream = fs, Url = fileInfo.Name, Overwrite = true }; Microsoft.SharePoint.Client.File uploadedFile = spFolder.Files.Add(fileCreationInfo); context.Load(uploadedFile); context.ExecuteQuery(); Console.WriteLine($"已上传: {fileInfo.FullName} -> {spFolder.ServerRelativeUrl}/{fileInfo.Name}"); } } // 处理子文件夹 foreach (DirectoryInfo subDirInfo in dirInfo.GetDirectories()) { Folder newSpFolder = spFolder.Folders.Add(subDirInfo.Name); context.Load(newSpFolder); context.ExecuteQuery(); UploadFolderContents(subDirInfo.FullName, newSpFolder, context); } } } }
2. REST API实现
通过HTTP请求直接调用SharePoint REST接口,适合无CSOM环境的场景,示例用PowerShell调用:
$siteUrl = "http://你的SharePoint站点URL" $libraryApiUrl = "$siteUrl/_api/web/lists/getbytitle('目标文档库名称')/rootfolder" $localFilePath = "C:\folder\file.txt" $targetFileName = "file.txt" $username = "domain\username" $password = ConvertTo-SecureString "你的密码" -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential($username, $password) # 读取文件并转为Base64编码 $fileBytes = [System.IO.File]::ReadAllBytes($localFilePath) $base64Content = [Convert]::ToBase64String($fileBytes) # 构建请求体 $requestBody = @{ __metadata = @{ type = "SP.File" } Content = $base64Content Overwrite = $true } | ConvertTo-Json # 发送POST请求上传文件 Invoke-RestMethod -Uri "$libraryApiUrl/files/add(overwrite=true,url='$targetFileName')" ` -Method Post ` -Credential $credential ` -Headers @{ "Accept" = "application/json;odata=verbose" "Content-Type" = "application/json;odata=verbose" } ` -Body $requestBody
内容的提问来源于stack exchange,提问作者GrandGTO
相关产品推荐
相关产品推荐

