Search code examples
sharepoint-onlinespfx

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);
                // })



Solution

  • 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