Hey there, SharePoint enthusiasts! Today, we’re diving into something super practical and often-requested—uploading files to SharePoint using the REST API. We’ll explore two approaches: one using plain ol’ JavaScript and another using PnPjs (a delightful library for simplifying SharePoint operations). I’ll also walk you through an example application in React, just to show how all this fits into a modern app setup. Let’s get to it!
Why File Uploads Matter
Uploading files might seem basic, but it’s fundamental for building robust applications. Whether it’s uploading user-generated content, storing documents, or automating backups, knowing how to handle file uploads gives you a ton of flexibility. Plus, with SharePoint being such a powerhouse for document management, this skill is a must-have!
Uploading Files with Plain JavaScript
First up, let’s talk about using plain JavaScript. This method is close to the metal and helps you understand what’s happening under the hood.
function uploadFileToSharePoint(file) {
const siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite";
const libraryName = "Documents"; // Update with your library name
const fileName = file.name;
fetch(`${siteUrl}/_api/web/getfolderbyserverrelativeurl('${libraryName}')/files/add(overwrite=true, url='${fileName}')`, {
method: 'POST',
headers: {
'Accept': 'application/json;odata=verbose',
'X-RequestDigest': document.getElementById('__REQUESTDIGEST').value
},
body: file
})
.then(response => response.json())
.then(data => console.log("File uploaded successfully", data))
.catch(error => console.error("Error uploading file: ", error));
}
Pros:
- No external dependencies: Great if you’re trying to keep things lightweight and avoid additional libraries.
- Full control: You can tweak every part of the request, from headers to request structure.
- Works everywhere: This approach works in any JavaScript environment, including SPFx, classic pages, and standalone applications.
Cons:
- Verbose: More code to handle errors, authentication, and responses compared to PnPjs.
- Handling large files: You’d need to implement chunked uploads manually if the file size exceeds SharePoint’s upload limits.
- More room for errors: Requires managing authentication, request headers, and digest tokens manually.
Best Practices:
- Always handle errors gracefully—show a user-friendly message rather than just logging the error.
- Keep security in mind—validate file types and sizes before uploading to prevent unnecessary storage usage.
- Use async/await instead of .then/.catch for cleaner and more readable code.
Uploading Files with PnPjs
PnPjs takes the pain out of SharePoint development. It’s like a trusty sidekick for SharePoint devs, handling common tasks with ease.
import { sp } from "@pnp/sp/presets/all";
import "@pnp/sp/files";
async function uploadFileWithPnPjs(file) {
const libraryName = "Documents";
try {
const response = await sp.web.getFolderByServerRelativePath(libraryName).files.addUsingPath(file.name, file, { Overwrite: true });
console.log("File uploaded successfully", response);
} catch (error) {
console.error("Error uploading file: ", error);
}
}
Pros:
- Simplified syntax: Less boilerplate code, making development faster and more maintainable.
- Handles authentication: Works seamlessly with modern authentication flows, reducing the need to manage tokens manually.
- Built-in error handling: Provides structured responses and error messages that help with debugging.
- Supports chunked uploads: If the file is large, PnPjs offers built-in chunking support for smooth uploads.
Cons:
- Library dependency: Adds an external dependency, increasing the project size slightly.
- Magic under the hood: Less transparency compared to raw JavaScript, which can be an issue if something goes wrong.
- Version compatibility: Since PnPjs is actively maintained, some older implementations may require updates over time.
Best Practices:
- Use PnPjs with modern SPFx projects—it’s built with TypeScript and integrates smoothly.
- Stay updated—PnPjs is actively maintained, so keep an eye on new features and deprecations.
- Handle exceptions properly—use try-catch and provide fallback mechanisms for failed uploads.
Application Sample: React File Upload
Here’s a quick and dirty React example, showing how you might use the PnPjs method in a component. React’s state management makes it easy to handle the file upload process.
import React, { useState } from 'react';
import { sp } from "@pnp/sp/presets/all";
const FileUpload = () => {
const [file, setFile] = useState(null);
const handleFileChange = (e) => {
setFile(e.target.files[0]);
};
const handleUpload = async () => {
if (file) {
try {
await sp.web.getFolderByServerRelativePath("Documents").files.addUsingPath(file.name, file, { Overwrite: true });
alert('File uploaded successfully!');
} catch (error) {
alert('Error uploading file. Check console for details.');
console.error(error);
}
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
<button onClick={handleUpload}>Upload</button>
</div>
);
};
export default FileUpload;
Use Cases:
- Building a document management app.
- Custom forms that require file uploads (like resumes, images, etc.).
- Automating uploads from user interactions.
Whether you’re going barebones with JavaScript or leveraging the power of PnPjs, understanding file uploads to SharePoint is a valuable tool in your developer toolkit. Pick the approach that fits your project’s needs—more control or more convenience!
Accounting.js Branding Cascading StyleSheet Cheat Sheet Connect Content Type CSS Currency Date Formats Dates Flows Hillbilly Tabs HTML5 Intl Javascript JavsScript JSON Format View Luxon NodeJs Numeral.js O365 OneDrive Out Of The Box Overflow Permissions PnP PowerAutomate Power Automate PowerShell Pwermissions ReactJs Rest Endpoint Send an HTTP Request to SharePoint SharePoint SharePoint Modern SharePoint Online SharePoint Tabs ShellScript SPFX SPO Styling Sync Teams App Transform JS TypeScript