How do I get item attachment using PnP caml?

Copper Contributor

I have this in my solution trying to use the accordion web part. The query I have, I've tried to dd attachment options with no luck:

 

 

   this.state = {
      items: new Array<any>(),
      choices: new Array<any>(),
      allowMultipleExpanded: this.props.allowMultipleExpanded,
      allowZeroExpanded: this.props.allowZeroExpanded,
    };
    this.getListItems();
    console.log(Items);
  }
  
private 
  private getListItems(): void {
    if (
      typeof this.props.listId !== "undefined" &&
      this.props.listId.length > 0 &&
      typeof this.props.columnTitle !== "undefined" &&
      this.props.columnTitle.length > 0 &&
      typeof this.props.selectedChoice !== "undefined" &&
      this.props.selectedChoice.length > 0
    ) {
      let orderByQuery = '';
      if (this.props.accordianSortColumn) {
        orderByQuery = `<OrderBy>
          <FieldRef Name='${this.props.accordianSortColumn}' ${this.props.isSortDescending ? 'Ascending="False"' : ''} />
        </OrderBy>`;
      }

      

      // let query = `<View>
      //   <Query>
      //     <Where>
      //       <Eq>
      //         <FieldRef Name='${this.props.columnTitle}'/>
      //         <Value Type='Text'>${this.props.selectedChoice}</Value>
      //       </Eq>
      //     </Where>
      //     ${orderByQuery}
      //   </Query>
      // </View>`;

            let query = `<View>
            <ViewFields>
          <FieldRef Name='Title'/>                                                                   
          <FieldRef Name='GUID'/>
          <FieldRef Name='Modified'/>
          </ViewFields>
        <Query>
          <Where>
            <Eq>
              <FieldRef Name='${this.props.columnTitle}'/>
              <Value Type='Text'>${this.props.selectedChoice}</Value>
            </Eq>
          </Where>
          ${orderByQuery}
        </Query>
      </View>`;

      let theAccordianList = sp.web.lists.getById(this.props.listId);
      theAccordianList
        .expand("AttachmentFiles")
        .getItemsByCAMLQuery({
          ViewXml: query,
        }) //.select("Title", "Answer", "Category")
        .then((results: Array<any>) => {
          this.setState({
            items: results,
          }); console.log(results)
        })
        .catch((error: any) => {
          console.log("Failed to get list items!");
          console.log(error);
        });

      //   let theAccordianList = sp.web.lists.getById(this.props.listId);
      // theAccordianList
      //   .getItemsByCAMLQuery({
      //     ViewXml: query,
      //   }) //.select("Title", "Answer", "Category")
      //   .then((results: Array<any>) => {
      //     this.setState({
      //       items: results,
      //     });
      //     console.log(this.state.items)
      //   })
      //   .catch((error: any) => {
      //     console.log("Failed to get list items!");
      //     console.log(error);
      //   });
    }
  }

  public componentDidUpdate(prevProps: IReactAccordionProps): void {
    if (prevProps.listId !== this.props.listId) {
      this.getListItems();
    }

    if (
      prevProps.allowMultipleExpanded !== this.props.allowMultipleExpanded ||
      prevProps.allowZeroExpanded !== this.props.allowZeroExpanded
    ) {
      this.setState({
        allowMultipleExpanded: this.props.allowMultipleExpanded,
        allowZeroExpanded: this.props.allowZeroExpanded,
      });
    }
  }

  public render(): React.ReactElement<IReactAccordionProps> {
    const listSelected: boolean =
      typeof this.props.listId !== "undefined" && this.props.listId.length > 0;
    const { allowMultipleExpanded, allowZeroExpanded } = this.state;
    return (
      <div className={styles.reactAccordion}>
        {!listSelected && (
          <Placeholder
            iconName="MusicInCollectionFill"
            iconText="Configure your web part"
            description="Select a list with a Title field and Content field to have its items rendered in a collapsible accordion format"
            buttonLabel="Choose a List"
            onConfigure={this.props.onConfigure}
          />
        )}
        {listSelected && (
          <div>
            <WebPartTitle
              displayMode={this.props.displayMode}
              title={this.props.selectedChoice}
              updateProperty={this.props.updateProperty}
            />
            <Accordion
              allowZeroExpanded={allowZeroExpanded}
              allowMultipleExpanded={allowMultipleExpanded}
            >
              {this.state.items.map((item: any) => {
                return (
                  <AccordionItem>
                    <AccordionItemHeading>
                      <AccordionItemButton
                        title={item[this.props.accordianTitleColumn]}
                      >
                        {item[this.props.accordianTitleColumn]}
                      </AccordionItemButton>
                    </AccordionItemHeading>
                    <AccordionItemPanel>
                      <p
                        dangerouslySetInnerHTML={{
                          __html: item[this.props.accordianContentColumn],
                        }}
                      />
                      items.att
                    </AccordionItemPanel>
                  </AccordionItem>
                );
              })}
            </Accordion>
          </div>
        )}
      </div>
    );
  }
}

 

 

 At the moment, the attachment field only returns true or false but I want the attachment URL to reference from the item. Does anyone know how to incorporate this and then render it?

 

Thank you.

1 Reply

@SpSouv 

 

There is no method available where you can get all attachments for all the list items from the list at single go. You need to do individual query for each item to get attachment URLs 

 

You can use below code to get attachment of particular items:

 

let item=sp.web.lists.getByTitle("TestList").items.getById(13);
    item.attachmentFiles.get().then((files)=>{
      console.log(files);
    })

 

Reference Link:

https://stackoverflow.com/questions/59899439/how-can-i-retrieve-a-sharepoint-list-items-attachments-...

https://pnp.github.io/pnpjs/sp/attachments/

 


Hope it will helpful to you and if so then Please mark my response as Best Response & Like to help others in this community