Often, in forums and SharePoint events, I receive a query on how to get all the attachments from all items in a SharePoint List. We can achieve this in several different ways as mentioned below.

Accessing the attachments folder from the SharePoint List using SharePoint Designer

Mapping the attachments folder to File Share.

Accessing the attachment folder of the list based on the path using a program

Get the attachments of each list item in a list using a program

Here, we are going to follow the last method for accessing the attachments in a list using PnP JavaScript library and render that in SharePoint Framework webpart.

First of all, create a SharePoint Framework webpart project using the Yeoman generator with the following command.

PS> yo @microsoft/sharepoint

Generate the project with No JavaScript option, because I am going to show the example without any JavaScript framework so that, you can use the snippet of any JavaScript framework on creating the webpart.

After the creation of the project, add the PnP JS library dependencies by running the following npm commmand.

PS> npm install –save @pnp/common @pnp/sp @pnp/logging @pnp/odata

To access the item and attachment objects using PnP library, add the following import statements to the webpart's TypeScript file.

import { sp, Item } from "@pnp/sp";

If we want to download or upload the attachment files from the webpart, we have to include the following import statement below the sp import statement.

The getSPData() method gets the attachment files from all items from the list “My List“. Add the “Attachments eq 1” to the filter to retrieve the items which contain attachments. Use the expand method to get the attachment files of the list items in a single request.

In response, we are generating the HTML as a list of attachment files with the associated Item Id and Title. The renderData() method adds the generated HTML to the webpart.

Replace the render() method with the below code snippet. This is used to call the getSPData() and update the retrieved values within the element pnpinfo.

public render(): void {

this.domElement.innerHTML = `

<div class="${ styles.pnPDemos}">

<div class="${ styles.container}">

<div class="${ styles.row}">

<div class="${ styles.column}">

<div id="pnpinfo"></div>

</div>

</div>

</div>

</div>`;

this.getSPData();

}

After running the webpart in the SharePoint page, it will display the Item id, title, and attachments. It will be nice to have a download link in the attachment file.