1
votes

I'm trying to upload a file using SPHttpClient in a spfx webpart.

The code I'm trying is

const spOpts:ISPHttpClientOptions={body: { my: "bodyJson" } };

contextDetails.spHttpClient.post(url,SPHttpClient.configurations.v1, spOpts) 
       .then(response => { 
          return response; 
        }) 
      .then(json => { 
        return json; 
      }) as Promise<any>

But I'm not sure how to add content of the file to this httpClient API.

I guess we have to add content of file to spOpts in body parameter. I'm not sure though.

Any help is appreciated. Thanks.

1

1 Answers

5
votes

Assuming that you are using and input file tag as below:

<input type="file" id="uploadFile" value="Upload File" />

<input type="button" class="uploadButton" value="Upload" />

You can then register the handler of the uploadButton as below:

private setButtonsEventHandlers(): void {    
    this.domElement.getElementsByClassName('uploadButton')[0].
    addEventListener('click', () => { this.UploadFiles(); });
}

Now, in the UploadFiles method, you can add the file's content and other necessary headers. Also, assuming that you are uploading the file to a document library, you can use the below snippet to upload a file to it. Modify it as per your site url and doc lib name:

var files = (<HTMLInputElement>document.getElementById('uploadFile')).files;
//in case of multiple files,iterate or else upload the first file.
var file = files[0];
if (file != undefined || file != null) {
  let spOpts : ISPHttpClientOptions  = {
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    },
    body: file        
  };

  var url = `https://<your-site-url>/_api/Web/Lists/getByTitle('Documents')/RootFolder/Files/Add(url='${file.name}', overwrite=true)`

  this.context.spHttpClient.post(url, SPHttpClient.configurations.v1, spOpts).then((response: SPHttpClientResponse) => {

    console.log(`Status code: ${response.status}`);
    console.log(`Status text: ${response.statusText}`);

    response.json().then((responseJSON: JSON) => {
      console.log(responseJSON);
    });
  });

}