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