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.

Viva Connections
Viva Connections
A Microsoft Viva module that provides a gateway to a modern engagement experience.
89 questions
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,118 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
10,060 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,766 questions
{count} votes

5 answers

Sort by: Most helpful
  1. Rob Windsor 1,961 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.

  2. Serkar Aydin 31 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.

  3. ezG 35 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);
    
    2 people found this answer helpful.
    0 comments No comments

  4. Tong Zhang_MSFT 9,141 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.

  5. Rijwan Ansari 746 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