简体   繁体   English

使用REST API将文件上传到SharePoint 2013

[英]File Upload to SharePoint 2013 using REST API

I have written this code 我已经写了这段代码

  $spSiteUrl = "http://mysharepoint/sites/site/web/"
  $cmd = "_api/web/lists/getbytitle('$docLib')/rootfolder/files/add(url='" + $file.Name + "', overwrite=true)"
  $digest = "got valid digest through code";
  $mediaType = new-object("System.Net.Http.Headers.MediaTypeWithQualityHeaderValue") "application/json"
  $handler = new-object("System.Net.Http.HttpClientHandler")
  $handler.UseDefaultCredentials= $true
  $client = New-Object("System.Net.Http.HttpClient") $handler        
  $client.BaseAddress = $spSiteUrl
  $client.DefaultRequestHeaders.Accept.Clear()    
  $client.DefaultRequestHeaders.Accept.Add($mediaType);
  $client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose")
  $content = $null
  $client.DefaultRequestHeaders.Add("X-HTTP-Method", "PUT")
  $client.DefaultRequestHeaders.Add("X-RequestDigest", $digest)
  $fileStream = [System.IO.File]::OpenRead($file.FullName)
  $streamContent = new-object ("System.Net.Http.StreamContent") $fileStream
  $task = $client.PostAsync($cmd, $streamContent)
  $response = $task.Result
  $content = $response.Content.ReadAsStringAsync().Result
  Write-Host $content
  $fileStream.Close()
  $fileStream.Dispose()
  $response = $response.EnsureSuccessStatusCode()
  $client.Dispose()

Here I already have a valid digest value which I got from doing a POST to _api/contextinfo 在这里,我已经有一个有效的摘要值,该值是通过对_api / contextinfo进行POST获得的

But when I execute this code I get an error 但是当我执行此代码时,我得到一个错误

{"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."}}} _api/web/lists/getbytitle('test')/rootfolder/files/add(url='BaselineFinishTag_2014_06.log', overwrite=true) {“ error”:{“ code”:“-2147024891,System.UnauthorizedAccessException”,“ message”:{“ lang”:“ en-US”,“ value”:“访问被拒绝。您无权执行此操作操作或访问此资源。“}}} _api / web / lists / getbytitle('test')/ rootfolder / files / add(url ='BaselineFinishTag_2014_06.log',overwrite = true)

Here as you can see that I am using UseDefaultCredentials to true. 在这里您可以看到我正在使用UseDefaultCredentials为true。 This code is running with an account which is the farm admin and site collection administrator and has complete ownership of the site where this code is being run. 此代码使用作为场管理员和网站集管理员的帐户运行,并且对正在运行此代码的网站具有完全所有权。

Can you tell me what I have missed in this code which is causing me to get UnAuthorizedException? 您能告诉我我在这段代码中遗漏了什么,导致我得到UnAuthorizedException吗?

Consuming the SharePoint 2013 REST API from PowerShell article describes how to perform CRUD operations using REST API in PowerShell. 从PowerShell中使用SharePoint 2013 REST API的文章介绍了如何在PowerShell中使用REST API执行CRUD操作。

The following function demonsrtates how to upload files via SharePoint 2013 REST using Invoke-RestSPO.ps1 function from the specified article: 以下函数演示了如何使用指定文章中的Invoke-RestSPO.ps1函数通过SharePoint 2013 REST上传文件:

How to upload File using REST API in PowerShell 如何在PowerShell中使用REST API上传文件

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
. ".\Invoke-RestSPO.ps1" #Load Invoke-RestSPO function

Function Upload-SPOFile(){

Param(
  [Parameter(Mandatory=$True)]
  [String]$WebUrl,

  [Parameter(Mandatory=$True)]
  [String]$UserName,

  [Parameter(Mandatory=$True)]
  [String]$Password, 

  [Parameter(Mandatory=$True)]
  [String]$FolderUrl,

  [Parameter(Mandatory=$True)]
  [System.IO.FileInfo]$FileInfo

)


   $Url = $WebUrl + "/_api/web/GetFolderByServerRelativeUrl('" + $FolderUrl + "')/Files/add(url='" + $FileInfo.Name + "',overwrite=true)"
   $FileContent = [System.IO.File]::ReadAllBytes($FileInfo.FullName)

   $contextInfo = Get-SPOContextInfo  $WebUrl $UserName $Password
   Invoke-RestSPO -Url $Url -Method Post -UserName $UserName -Password $Password -Body $FileContent  -RequestDigest $contextInfo.GetContextWebInformation.FormDigestValue
}



#Usage: upload file into SharePoint Online  
$UserName = "username@contoso.onmicrosoft.com"
$Password = Read-Host -Prompt "Enter the password"    
$WebUrl = "https://contoso.sharepoint.com/"
$FolderUrl = "/Shared Documents"
$UploadFileInfo = New-Object System.IO.FileInfo("C:\Users\user\Documents\SharePoint User Guide.docx")


Upload-SPOFile -WebUrl $WebUrl -UserName $UserName -Password $Password -FolderUrl $FolderUrl -FileInfo $UploadFileInfo

References 参考文献

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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