Thursday 5 March 2020

Add Attachment is List using spHttpClient in SPFX React webpart

Below code can be used to add attachment in SPFx webpart using spHttpClient or PnP

import { SPHttpClient, SPHttpClientResponse,ISPHttpClientOptions } from '@microsoft/sp-http';

HTML:

<input type="file" name="Attachment" style={{ paddingTop: '5px' }} id="FileAttachment"></input>

JS:

let file = (document.querySelector("#FileAttachment") as HTMLInputElement).files[0];        
          if (file) { 
              let spOpts : ISPHttpClientOptions  = {
                headers: {
                  "Accept": "application/json",
                  "Content-Type": "application/json"
                },
                body: file       
              };
              var url = this.props.siteURL + `/_api/web/lists(guid'` + Taskitem.ParentListID + `')/items` + `('` + Taskitem.ParentItemID + `')` + `/AttachmentFiles/add(FileName='` + file.name +`')`;
              this.props.context.spHttpClient.post(url, SPHttpClient.configurations.v1, spOpts).then((response: SPHttpClientResponse) => {
                console.log(`Status code: ${response.status}`);
                console.log(`Status text: ${response.statusText}`);
                if(Number(`${response.status}`) >300)
                {
                  alert('Error Uploading file, Try again or contact IT');
                  this._closeDialog();
                  return;
                }
                response.json().then((responseJSON: JSON) => {
                  console.log(responseJSON);                 
                });
              });            
          }

        
     
If you want to use pnp then below code can be used:

         var item = sp.web.lists.getById(Taskitem.ParentListID).items.getById(Taskitem.ParentItemID);
             item.attachmentFiles.add(file.name, file).then(v => {
                    //console.log('Check');
             });


Update list id and item id accordingly.

I have tested uploading 10MB files and it uploaded with in couple of seconds.

Happy Coding!

4 comments: