Have to upload files into Sharepoint online using Graph API

Sunny Rastogi 106 Reputation points
2022-07-23T11:24:29.853+00:00

Hi All,

I want to upload small and large documents into SharePoint online document library using Microsoft API.

Please help me how to do it and where I will have to write the code.

Looking for your feedback.

Microsoft 365 and Office Microsoft Viva Viva Connections
Microsoft 365 and Office SharePoint Development
Microsoft 365 and Office SharePoint For business Windows
Microsoft Security Microsoft Graph
{count} votes

5 answers

Sort by: Most helpful
  1. ezG 50 Reputation points
    2023-09-10T06:57:14.4366667+00:00

    IF YOU'RE USING VERSION 5 OF MICROSOFT GRAPH SDK ("Request()" has been deprecated from the Fluent UI)

    var item = await graphClient
        .Drives[driveId]
        .Root
        .ItemWithPath(spPath)
        .Content
        .PutAsync(stream);
    
    5 people found this answer helpful.
    0 comments No comments

  2. Rob Windsor 2,001 Reputation points
    2022-07-25T12:01:50.51+00:00

    This Microsoft Learn module demonstrates how to upload both small and large files to SharePoint Online using Microsoft Graph.

    Access Files with Microsoft Graph

    The code to upload a small file is relatively simple.

    var fileName = "smallfile.txt";  
    var filePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);  
    Console.WriteLine("Uploading file: " + fileName);  
      
    FileStream fileStream = new FileStream(filePath, FileMode.Open);  
    var uploadedFile = client.Me.Drive.Root  
                                  .ItemWithPath("smallfile.txt")  
                                  .Content  
                                  .Request()  
                                  .PutAsync<DriveItem>(fileStream)  
                                  .Result;  
    Console.WriteLine("File uploaded to: " + uploadedFile.WebUrl);  
    

    The code to upload a larger file requires chunking.

    var fileName = "largefile.zip";  
    var filePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);  
    Console.WriteLine("Uploading file: " + fileName);  
      
    // load resource as a stream  
    using (Stream stream = new FileStream(filePath, FileMode.Open))  
    {  
        var uploadSession = client.Me.Drive.Root  
                                        .ItemWithPath(fileName)  
                                        .CreateUploadSession()  
                                        .Request()  
                                        .PostAsync()  
                                        .Result;  
      
        // create upload task  
        var maxChunkSize = 320 * 1024;  
        var largeUploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, stream, maxChunkSize);  
      
        // create progress implementation  
        IProgress<long> uploadProgress = new Progress<long>(uploadBytes =>  
        {  
            Console.WriteLine($"Uploaded {uploadBytes} bytes of {stream.Length} bytes");  
        });  
      
        // upload file  
        UploadResult<DriveItem> uploadResult = largeUploadTask.UploadAsync(uploadProgress).Result;  
        if (uploadResult.UploadSucceeded)  
        {  
            Console.WriteLine("File uploaded to user's OneDrive root folder.");  
        }  
    }  
    
    3 people found this answer helpful.

  3. Rijwan Ansari 766 Reputation points MVP
    2023-01-11T12:59:56.56+00:00

    Hi

    You can upload files to SharePoint Online using any programming language with Graph API.

    Example: [https://stackoverflow.com/questions/49776955/how-to-upload-a-large-document-in-c-sharp-using-the-microsoft-graph-api-rest-cal

    1 person found this answer helpful.
    0 comments No comments

  4. Serkar Aydin 36 Reputation points
    2023-01-04T11:55:54.927+00:00

    Hi,

    not sure if the code helped you. I wrote a code in PowerShell, which might help you too.
    https://sposcripts.com/how-to-upload-files-to-sharepoint-using-graph-api/

    Param (  
        $Tenant = "m365x323732",  
        $AppID = "e0b8aefa-cb52-4bda-93a0-7d87120bcdbb",  
        $SiteID = "e35cee33-6d10-4e2c-a83b-496a26062ad3",  
        $LibraryURL = "https://m365x323732.sharepoint.com/sites/SalesAndMarketing/Shared%20Documents",  
        $Path = "C:\Users\Serkar\Desktop\security.png"  
    )  
      
    $AppCredential = Get-Credential($AppID)  
      
    #region authorize  
    $Scope = "https://graph.microsoft.com/.default"  
      
    $Body = @{  
        client_id = $AppCredential.UserName  
        client_secret = $AppCredential.GetNetworkCredential().password  
        scope = $Scope  
        grant_type = 'client_credentials'  
    }  
      
    $GraphUrl = "https://login.microsoftonline.com/$($Tenant).onmicrosoft.com/oauth2/v2.0/token"  
    $AuthorizationRequest = Invoke-RestMethod -Uri $GraphUrl -Method "Post" -Body $Body  
    $Access_token = $AuthorizationRequest.Access_token  
      
    $Header = @{  
        Authorization = $AuthorizationRequest.access_token  
        "Content-Type"= "application/json"  
    }  
    #endregion  
      
    #region get drives  
      
      
    $GraphUrl = "https://graph.microsoft.com/v1.0/sites/$SiteID/drives"  
      
    $BodyJSON = $Body | ConvertTo-Json -Compress  
    $Result = Invoke-RestMethod -Uri $GraphUrl -Method 'GET' -Headers $Header -ContentType "application/json"   
    $DriveID = $Result.value| Where-Object {$_.webURL -eq $LibraryURL } | Select-Object id -ExpandProperty id  
      
    If ($DriveID -eq $null){  
      
        Throw "SharePoint Library under $LibraryURL could not be found."  
    }  
      
    #endregion  
      
    #region upload file  
      
    $FileName = $Path.Split("\")[-1]  
    $Url  = "https://graph.microsoft.com/v1.0/drives/$DriveID/items/root:/$($FileName):/content"  
      
    Invoke-RestMethod -Uri $Url -Headers $Header -Method Put -InFile $Path -ContentType 'multipart/form-data' -Verbose  
    #endregion   
    
    2 people found this answer helpful.

  5. Tong Zhang_MSFT 9,251 Reputation points
    2022-07-25T07:33:53.67+00:00

    Hi @Sunny Rastogi ,

    According to my research and testing, you can use the following Graph API to upload files to SharePoint drive:

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

    If you want to upload large files, you can upload large files with an upload session , please try to use the following Graph API to create an upload session:

    POST /sites/{siteId}/drive/items/{itemId}/createUploadSession  
    

    More information for reference:
    Upload small files: Upload or replace the contents of a DriveItem (Note: This method only supports files up to 4MB in size.)
    Upload large files: Upload large files with an upload session


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.