Microsoft 365  

OneDrive File Management with Graph API in SPFx

Introduction

OneDrive is the personal file storage solution in Microsoft 365, allowing users to securely store and access files from anywhere. Developers often need to provide employees with tools to automate, manage, or interact with their OneDrive content directly from custom portals.

With SharePoint Framework (SPFx) and the Microsoft Graph API, developers can build solutions to upload, download, and organize OneDrive content seamlessly.

Why Use Graph API for OneDrive in SPFx?

  • Unified access → Interact with OneDrive using a single Graph endpoint.

  • Delegated access → Users can manage only their own content.

  • Secure authentication → SPFx uses Azure AD seamlessly.

Key Operations in OneDrive

1. List Files in Root Folder

This call retrieves all files and folders located in the root of the user’s OneDrive.

const client = await this.context.msGraphClientFactory.getClient("3");
const response = await client.api("/me/drive/root/children").get();
console.log(response.value);

2. Create a Folder

This request creates a new folder inside the user’s OneDrive root directory.

const folder = {
  name: "Reports",
  folder: {},
  "@microsoft.graph.conflictBehavior": "rename",
};

await client.api("/me/drive/root/children").post(folder);

3. Upload a File

This uploads a text file (sample.txt) into the "Reports" folder.

const fileContent = new Blob(["Hello from Graph API"], { type: "text/plain" });

await client
  .api("/me/drive/root:/Reports/sample.txt:/content")
  .put(fileContent);

4. Download a File

This fetches the contents of a file from OneDrive for reading or processing.

const file = await client
  .api("/me/drive/root:/Reports/sample.txt:/content")
  .get();
console.log(file);

5. Delete a File

This removes a specific file permanently from OneDrive.

await client.api("/me/drive/root:/Reports/sample.txt").delete();

Best Practices for OneDrive Integration

  1. Use delegated permissions for security.

  2. Implement upload sessions for files >4MB.

  3. Use $select for performance optimization.

  4. Add caching to avoid redundant API calls.

Real-World Example

Imagine a personal dashboard web part where users can quickly create folders for new projects and upload files without leaving the intranet portal.

Conclusion

SPFx combined with Graph API makes OneDrive file management seamless, secure, and user-friendly. From simple file uploads to advanced folder automation, developers can provide business users with powerful tools inside Microsoft 365.