Pete Whelan
Pete Whelan

Reputation: 95

Getting attachment info from list?

EDIT: It does work now if I do

const item: IItem = sp.web.lists.getByTitle(this.properties.listName).items.getById(51);

but not if I do

const item: IItem = sp.web.lists.getByTitle(this.properties.listName).items.getById(Number(r[i]["ID"]));

Thanks P

Initial Problem: I can read items from a list into an SPFx web part. I am having trouble getting a list of the attachments that each item might have.

I try this below but I get the error

TypeError: u.attachmentFiles is not a function

Thanks P

const r = await sp.web.lists.getByTitle("MyList").getItemsByCAMLQuery({
        ViewXml: this.properties.camlQuery,
    });

      

    // look through the returned items.
    for (var i = 0; i < r.length; i++) {


console.log('ID:' + r[i]["ID"]);



                //const item: IItem = sp.web.lists.getByTitle(this.properties.listName).items.getById(r[i]["ID"]);
                const item: IItem = sp.web.lists.getByTitle(this.properties.listName).items.getById(51);

                console.log('got by id');

                // get all the attachments
                const attachmentInfo: IAttachmentInfo[] = await item.attachmentFiles();
//TypeError: u.attachmentFiles is not a function

                console.log('got attachmentInfo');

                // attachmentInfo.map(file=>{
                //   var fileType=file.FileName.split('.').pop();
                //   var fileUrl=file.ServerRelativeUrl;
                //   //attachs.push({"fileType":fileType,"fileUrl":fileUrl});
                //   console.log('fileType:' + fileType);
                //   console.log('fileUrl:' + fileUrl);
                // })


Upvotes: 0

Views: 836

Answers (2)

Zella_msft
Zella_msft

Reputation: 372

based on my research and testing, please try to use the following code to get list item attachments:

import { sp } from "@pnp/sp/presets/all";
import { IAttachmentInfo } from "@pnp/sp/attachments";
import { IItem } from "@pnp/sp/items/types";

(async () => {
  // get list item by id
  const item: IItem = sp.web.lists.getByTitle("React").items.getById(2);
  // get all attachments
  const attachments: IAttachmentInfo[] = await item.attachmentFiles();
  console.table(attachments);
})().catch(console.log)

More information for reference: Working With SharePoint List Item Attachments Using PnP JS In SPFx

Hope it can help you. Thanks for your understanding.

Upvotes: 1

devil_inside
devil_inside

Reputation: 450

The code looks fine. To get it work you need to have all imports. I guess you are missing

import "@pnp/sp/attachments";

like mentioned here: https://pnp.github.io/pnpjs/sp/attachments

And to read more about why it is like that read here (in short: to make the package size as small as possible): https://pnp.github.io/pnpjs/concepts/selective-imports

Upvotes: 2

Related Questions