Sharepoint Online upload files to library with PnP-JS-Core 2.0.7
-
30-12-2020 - |
Frage
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!
Lösung
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!");
});
});
});
}
}
Andere Tipps
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.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit sharepoint.stackexchange