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:
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!
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!
It Works very well, this is just what I'm looking for.
ReplyDeleteMany thanks for this helpfull post.
Add Attachment is List using spHttpClient in SPFX React webpart
ReplyDeleteInteresting post..
Microsoft Sharepoint development services
Top 5 Key Features of SharePoint Development that you should know
This comment has been removed by the author.
ReplyDeleteVery useful,,
ReplyDeleteread this blog..
Iqra technology