download a sharepoint list in typescript

To download a SharePoint list using TypeScript, you can make use of the SharePoint REST API. Here's an example code snippet to download a SharePoint list in TypeScript:

index.ts
import { sp } from "@pnp/sp";

// Specify the web URL and the list name
const webUrl: string = "https://your-web-url";
const listName: string = "Your List Name";

// Get the list
const list = sp.web.getList(`${webUrl}/_api/lists/GetByTitle('${listName}')`);

// Fetch the list items
list.items.select("FileRef").get().then((items) => {
  // Iterate over the list items and initiate the download
  items.forEach((item) => {
    const fileUrl: string = item.FileRef;
    const fileName: string = fileUrl.split("/").pop();
    const fullUrl: string = `${webUrl}${fileUrl}`;

    fetch(fullUrl).then((response) => response.blob())
    .then((blob) => {
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    })
    .catch((err) => console.log(err));
  });
});
985 chars
31 lines

In the above code, we first import the sp object from the @pnp/sp package. We then specify the web URL and the list name, and get the list using the getList method of sp.web.

We then fetch the list items using the select and get methods. In the select method, we specify the fields we want to include in the response (in this case, just the FileRef field which contains the relative file URL).

For each list item, we initiate the download by fetching the file using the fetch method and creating a blob from the response. We then create a URL from the blob, add a link element to the DOM, simulate a click on the link to initiate the download, and then remove the link element.

Note that this code assumes that all files in the list have unique names. If this is not the case, you may need to include additional logic to ensure that file names are unique before initiating the download.

gistlibby LogSnag