File Upload to SharePoint 2013 using REST API

2020-08-04 10:39发布

问题:

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

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)

Here as you can see that I am using UseDefaultCredentials to 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?

回答1:

Consuming the SharePoint 2013 REST API from PowerShell article describes how to perform CRUD operations using REST API in PowerShell.

The following function demonsrtates how to upload files via SharePoint 2013 REST using Invoke-RestSPO.ps1 function from the specified article:

How to upload File using REST API in PowerShell

[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

  • Invoke-RestSPO.ps1
  • Consuming the SharePoint 2013 REST API from PowerShell