Forum Discussion

Pulak2409's avatar
Pulak2409
Brass Contributor
Mar 22, 2019
Solved

SharePoint file upload using API

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. https://github.com/SharePoint/PnP-JS-Core/wiki/Working-With:-Files 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.

Resources