This repository has been archived by the owner on Aug 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 232
Working With: Attachments
Patrick Rodgers edited this page Jan 31, 2017
·
8 revisions
The ability to attach file to list items allows users to track documents outside of a document library. You can use the PnP JS Core library to work with attachments as outlined below.
import pnp from "sp-pnp-js";
let item = pnp.sp.web.lists.getByTitle("MyList").items.getById(1);
// get all the attachments
item.attachmentFiles.get().then(v => {
console.log(v);
});
// get a single file by file name
item.attachmentFiles.getByName("file.txt").get().then(v => {
console.log(v);
});
// select specific properties using odata operators
item.attachmentFiles.select("ServerRelativeUrl").get().then(v => {
console.log(v);
});
You can add an attachment to a list item using the add method. This method takes either a string, Blob, or ArrayBuffer.
import pnp from "sp-pnp-js";
let item = pnp.sp.web.lists.getByTitle("MyList").items.getById(1);
item.attachmentFiles.add("file2.txt", "Here is my content").then(v => {
console.log(v);
});
You can read the content of an attachment as a string, Blob, ArrayBuffer, or json using the methods supplied.
import pnp from "sp-pnp-js";
let item = pnp.sp.web.lists.getByTitle("MyList").items.getById(1);
item.attachmentFiles.getByName("file.txt").getText().then(v => {
console.log(v);
});
// use this in the browser, does not work in nodejs
item.attachmentFiles.getByName("file.mp4").getBlob().then(v => {
console.log(v);
});
// use this in nodejs
item.attachmentFiles.getByName("file.mp4").getBuffer().then(v => {
console.log(v);
});
// file must be valid json
item.attachmentFiles.getByName("file.json").getJSON().then(v => {
console.log(v);
});
You can also update the content of an attachment. This API is limited compared to the full file API - so if you need to upload large files consider using a document library.
import pnp from "sp-pnp-js";
let item = pnp.sp.web.lists.getByTitle("MyList").items.getById(1);
item.attachmentFiles.getByName("file2.txt").setContent("My new content!!!").then(v => {
console.log(v);
});
import pnp from "sp-pnp-js";
let item = pnp.sp.web.lists.getByTitle("MyList").items.getById(1);
item.attachmentFiles.getByName("file2.txt").delete().then(v => {
console.log(v);
});
Sharing is caring!