1

How do I upload a file with all properties or fields values to a sharepoint library?

I'm using PnP-JS-Core 2.0.7

Thanks!

1
  • What have you tried till now ? What issues did you face ? Can share some related code of your attempts? Aug 12, 2017 at 5:39

2 Answers 2

3

You can try the below approach using the FileReader API :

Assume that you have html structure somewhat as mentioned below:

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

<input type="button" value="Upload" onclick="UploadFiles()" />

Now, in your UploadFiles method, you can upload the file using getFolderByServerRelativeUrl("server-relative-url").files.add method and after that you get the uploaded files ID and then update its properties as below:

function UploadFiles() {
    var files = 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){

    //assuming that the name of document library is Documents, change as per your requirement, 
    //this will add the file in root folder of the document library, if you have a folder named test, replace it as "/Documents/test"
    pnp.sp.web.getFolderByServerRelativeUrl("/Documents").files.add(file.name, file, true).then((result) => {
        console.log(file.name + " upload successfully!");
          result.file.listItemAllFields.get().then((listItemAllFields) => {
             // get the item id of the file and then update the columns(properties)
            pnp.sp.web.lists.getByTitle("Documents").items.getById(listItemAllFields.Id).update({
                        Title: "My New Title",
                        Description: "Here is a new description"
            }).then(r=>{
                        console.log(file.name + " properties updated successfully!");
            });           
        }); 
    });
  }
}
1
  • document.getElementById('uploadFile').files throws error for me saying "Property 'files' does not exist on type 'HTMLElement". When I try to use "<HTMLInputElement>" for casting, it throws error "JSX element type 'HTMLInputElement' is not a constructor function for JSX elements"..... Any ideas how to resolve this? Any help is much appreciated
    – zainul
    Mar 13, 2019 at 5:38
0

There is good example on the pnp js core github here. Although example is in typescript you can get the idea which I have also used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.