Methods on how to Add Attachments to SharePoint List


When working with SharePoint lists, you might find yourself in a situation where you need to attach files to a list item. This is especially useful for document approvals, storing additional details, or just keeping relevant files together. Thankfully, SharePoint provides multiple ways to achieve this, including the SharePoint REST API, PnPjs, and PnP PowerShell. In this blog, we’ll go over how to add attachments using each of these methods, along with their advantages, disadvantages, and use cases.


Prerequisites

Before you start, ensure you have:

  • Proper permissions to add attachments to SharePoint list items.
  • A SharePoint list where you want to upload attachments.
  • Necessary dependencies (PnPjs for JavaScript, PnP PowerShell module for PowerShell).

1. Adding an Attachment Using SharePoint REST API and JavaScript

The SharePoint REST API allows you to interact with SharePoint data using HTTP requests. If you’re working with JavaScript in a custom solution, here’s how you can add an attachment to a list item.

Steps to Follow:
  1. Get the list item’s ID.
  2. Upload the file as an attachment to the item.
const siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite";
const listName = "YourListName";
const itemId = 1; // Replace with your actual item ID
const fileInput = document.getElementById("fileUpload");

fileInput.addEventListener("change", async function () {
    const file = fileInput.files[0];
    if (!file) return;
    
    const reader = new FileReader();
    reader.onload = async function (event) {
        const fileContent = event.target.result;
        const endpoint = `${siteUrl}/_api/web/lists/getbytitle('${listName}')/items(${itemId})/AttachmentFiles/add(FileName='${file.name}')`;
        
        const response = await fetch(endpoint, {
            method: "POST",
            headers: {
                "Accept": "application/json;odata=verbose",
                "Content-Type": "application/json;odata=verbose",
                "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
            },
            body: fileContent
        });
        
        if (response.ok) {
            console.log("Attachment added successfully!");
        } else {
            console.error("Error uploading attachment:", response.statusText);
        }
    };
    reader.readAsArrayBuffer(file);
});
Key Takeaways:
  • We read the file and send it as a POST request to SharePoint.
  • The X-RequestDigest is required to prevent Cross-Site Request Forgery (CSRF) attacks.
  • The readAsArrayBuffer() method reads the file data properly for SharePoint to accept it.
Advantages & Disadvantages:
  • ✅ Provides direct API interaction and control over requests.
  • ✅ Can be used in client-side applications without additional dependencies.
  • ❌ Requires handling of request headers and security tokens.
  • ❌ More complex compared to PnPjs.
Use Cases:
  • Custom SharePoint forms requiring file attachments.
  • Integration with third-party JavaScript applications.

2. Adding an Attachment Using PnPjs

PnPjs makes working with SharePoint data in JavaScript much easier with cleaner, more readable code. Here’s how you can achieve the same functionality using PnPjs:

import "@pnp/sp/attachments";
import { sp } from "@pnp/sp/presets/all";

async function addAttachment(listName, itemId, file) {
    try {
        const response = await sp.web.lists.getByTitle(listName).items.getById(itemId).attachmentFiles.add(file.name, file);
        console.log("Attachment added:", response);
    } catch (error) {
        console.error("Error adding attachment:", error);
    }
}

// Usage Example:
const fileInput = document.getElementById("fileUpload");
fileInput.addEventListener("change", function () {
    const file = fileInput.files[0];
    if (file) {
        addAttachment("YourListName", 1, file);
    }
});
Why PnPjs?
  • Shorter Code: The library abstracts away much of the complexity.
  • Promises & Async/Await Support: No need to manually handle fetch requests.
  • Error Handling: Built-in mechanisms help with debugging and handling failures.
Advantages & Disadvantages:
  • ✅ Shorter and cleaner code compared to REST API.
  • ✅ Built-in authentication and request handling.
  • ✅ Supports modern async/await syntax.
  • ❌ Requires adding PnPjs as a dependency.
  • ❌ Might not provide as much control as raw REST API requests.
Use Cases:
  • SharePoint Framework (SPFx) web parts.
  • Modern SharePoint customizations using JavaScript.

3. Adding an Attachment Using PnP PowerShell

If you prefer working with PowerShell (or need to automate things), PnP PowerShell provides an easy way to add attachments to a SharePoint list item.

PowerShell Script to Add a Single Attachment
# Define variables
$siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite"
$listName = "YourListName"
$itemId = 1  # Replace with actual item ID
$filePath = "C:\Path\To\Your\File.txt"

# Connect to SharePoint Online
Connect-PnPOnline -Url $siteUrl -UseWebLogin

# Add Attachment
Add-PnPListItemAttachment -List $listName -Identity $itemId -Path $filePath

Write-Host "Attachment added successfully!"

PowerShell Script to Add Multiple Attachments

$files = @("C:\Path\To\File1.txt", "C:\Path\To\File2.pdf")
foreach ($file in $files) {
    Add-PnPListItemAttachment -List $listName -Identity $itemId -Path $file
    Write-Host "Added attachment: $file"
}
Why Use PnP PowerShell?
  • Best for Automation: Easily integrate with scripts to automate SharePoint tasks.
  • Simple and Readable: Much easier than writing raw REST API calls in PowerShell.
  • Works for Bulk Operations: Can be used to upload multiple attachments at once.
Advantages & Disadvantages:
  • ✅ Ideal for automation and batch processing.
  • ✅ Simple and easy-to-read syntax.
  • ✅ Works well for bulk operations.
  • ❌ Requires PowerShell and PnP module installation.
  • ❌ Not suitable for real-time user interactions in the browser.
Use Cases:
  • Automated workflows for SharePoint list management.
  • Bulk uploads of attachments to multiple list items.

Summary Table
MethodProsConsUse Cases
REST APIFull control, no dependenciesRequires manual request handlingCustom JavaScript apps
PnPjsEasy to use, cleaner syntaxRequires PnPjs librarySPFx web parts, modern customization
PnP PowerShellGreat for automation and bulk uploadsNeeds PowerShell and PnP moduleBatch processing, admin tasks

Adding attachments to SharePoint list items can be done in various ways, depending on your needs:

  • REST API + JavaScript: Great for direct API interaction but requires handling requests manually.
  • PnPjs: Clean, modern, and optimized for JavaScript developers.
  • PnP PowerShell: Perfect for automation and bulk uploads.

If you’re developing a SharePoint solution, PnPjs is often the best option because of its simplicity and flexibility. However, for automation tasks, PnP PowerShell is the way to go.


Accounting.js Admins Branding Connect Content Type CSS Currency Dates Flows GULP Hillbilly Tabs Javascript JavsScript JSON Format View Luxon Myths NodeJs 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 Tags Taxonomy Termstore Transform JS TypeScript Versioning

Leave a Comment

Your email address will not be published. Required fields are marked *