Delete File Version By Version Id in SharePoint using JSOM

The example in this topic show how to use JSOM to Delete File Version By Version Id in SharePoint

  • var oItems, clientContext;
  • function DeleteFileVersionByVersionId() {
  •     // You can optionally specify the Site URL here to get the context
  •     // If you don't specify the URL, the method will get the context of the current site
  •     // var clientContext = new SP.ClientContext("http://MyServer/sites/SiteCollection");
  •     clientContext = new SP.ClientContext();
  •  
  •     // Get List Object
  •     var olistCollection = clientContext.get_web().get_lists();
  •     var oList = olistCollection.getByTitle("Documents");
  •  
  •     // Get Item using CAML Query
  •     var camlQuery = new SP.CamlQuery();
  •     camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'FileLeafRef\'/>' + '<Value Type=\'File\'>Document.docx</Value></Eq></Where></Query></View>');
  •     oItems = oList.getItems(camlQuery);
  •  
  •     // Load List Item collection object
  •     clientContext.load(oItems);
  •  
  •     // Execute the query to the server.
  •     clientContext.executeQueryAsync(onsuccess, onfailed);
  • }
  •  
  • function onsuccess() {
  •     // Loop through each Item.
  •     var itemCount = oItems.get_count();
  •     for (var i = 0; i <= itemCount - 1; i++) {
  •         // Get File object of the list item
  •         var oFile = oItems.itemAt(i).get_file();
  •  
  •         // Delete File verion using version Id
  •         // NOTE: Every Major check In will be incremented by "512" e.g. version 1.0 will have ID = 512, Version 2.0 will have ID = 1024
  •         // Every Minor check in will be incremented by "1" e.g version 0.1 will have ID = 1 , version 0.2 will have ID = 2
  •         oFile.get_versions().deleteByID(2054);
  •         break;
  •     }
  •  
  •     //Execute the batch
  •     clientContext.executeQueryAsync(FinalQuerySuccess, FinalQueryFailure);
  • }
  •  
  • function onfailed(sender, args) {
  •     console.log('Failed' + args.get_message() + '\n' + args.get_stackTrace());
  • }
  •  
  • function FinalQuerySuccess(sender, args) {
  •     console.log('Success');
  • }
  •  
  • function FinalQueryFailure(sender, args) {
  •     console.log('Failed' + args.get_message() + '\n' + args.get_stackTrace());
  • }

Thank you for reading this article. This code was tested in SharePoint 2013


© 2019 Code SharePoint