SOLVED

SharePoint file upload using API

Brass Contributor

Is there any API available to upload file in SharePoint? Sample code will be helpful.

 

If we upload same file using API will it replace the old file or create a new version of the file? Please advise.

 

2 Replies

Hey @Pulak2409 ,

 

I recommend you use PnPJs, since it makes handling REST calls a lot easier for you. This page shows how to work with files using it. A good point is that, after uploading the file, you may want to update it to set the Title of the Item you just created. Here is a piece of my code, which uploads from an input button. Any problem, let me know!

 

$("input").change(e => {
e.preventDefault();
let input: HTMLInputElement = <HTMLInputElement>jQuery(e.target)[0];
let file = input.files[0];
if (!file || file.size == 0)
alert("Arquivo Inválido");
else{
sp.web.lists.getByTitle("Documents").rootFolder.files.add(file.name, file, true).then(f => {
f.file.getItem().then(item => {
let file = new Object();
file.Title = "MyTitle";
item.update(file).then(() => {
return true;
});
});
});
}
});
 
Edit: Sorry for the indenting. They won't let me fix it.
best response confirmed by VI_Migration (Silver Contributor)
Solution

@Pulak2409 Multiple APIs to do this.

REST API https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest

You can also use CSOM using FileCreationInformation https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/upload-large-files-sample-app-for-...

You have the option to overwrite files in both scenarios

1 best response

Accepted Solutions
best response confirmed by VI_Migration (Silver Contributor)