Share via


Uploading a File to SharePoint Online using Microsoft Graph API

Question

Tuesday, June 9, 2020 12:28 PM

Hello,

I'm really new to Microsoft Graph API, I created a script using powershell to get reports from Microsoft 365 and it is being saved on my drive (c:\temp\reports.xlsx).

After it is being saved i wish to upload it to SharePoint online. On reading the docs, Microsoft says to do the following request,

PUT /sites/{site-id}/drive/items/{parent-id}:/{filename}:/content

I then tried to apply it to my use case and this was my request:

$upLoadRequest = "https://graph.microsoft.com/v1.0/sites/tenant.sharepoint.com/drive/items/Test:/$($File):/content"

The `$File` variable contains c:\temp\reports.xlsx the directory where my excel file is saved on getting the reports. The `Test` in my Url is a folder I created in `Documents` on my Site. But while doing the request I get this: 

StatusCode: 400 
StatusDescription: Bad Request

Please Help!

Thanks

All replies (1)

Wednesday, June 10, 2020 9:03 AM

Hi,

Sample test script for your reference.

Connect-PnPOnline -AppId 'yourAzure app id' -AppSecret "yourAzure app secret" -AADDomain 'xxx.onmicrosoft.com'
$accessToken= Get-PnPAccessToken
$apiUrl = "https://graph.microsoft.com/v1.0/sites/xxx.sharepoint.com,x,x/drives/driveid/items/01AKXHS4ELSEOTLPZHZZDYYBOW57WR6HK6:/test.xlsx:/content"
$path="C:\Lee\Script\testdata.xlsx"
$file=[IO.File]::ReadAllBytes($path)
Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Put -Body $file -ContentType "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

For file content types, check below thread.

https://community.box.com/t5/Platform-and-Development-Forum/Upload-a-file-using-API-in-PowerShell/td-p/35660

Best Regards,

Lee

Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact [email protected].

SharePoint Server 2019 has been released, you can click here to download it.
Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.