Search This Blog

Thursday, September 26, 2019

SharePoint online rename filename for document Library using JSOM



Step 1: Add script editor on your page
step 2: refer jQuery
Step 3: Copy paste below one : Note : rename your site url

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="/sites/DeveloperSite/SiteAssets/jquery.min.js"></script>
<script>
    function fileRenameChange() {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
            var context = SP.ClientContext.get_current();
            var web = context.get_web();
            var list = web.get_lists().getByTitle("Documents");
            var vFolder = $('#txtFolder').val();
            var vPrefix = $('#txtPrefix').val();
            context.load(list);
            context.executeQueryAsync(function (data) {             
                try {
                    var files;
                    var context = new SP.ClientContext.get_current();
                 
                    var folderServerRelativeUrl = "/sites/DeveloperSite/Shared%20Documents/" + vFolder;
                    var folder = context.get_web().getFolderByServerRelativeUrl(folderServerRelativeUrl);
                    files = folder.get_files();
                    context.load(files);
                    context.executeQueryAsync(function (sender, args) {
                        var listItemEnumerator = files.getEnumerator();
                        while (listItemEnumerator.moveNext()) {
                            var fileUrl = listItemEnumerator.get_current().get_serverRelativeUrl();
                            var neurl = listItemEnumerator.get_current().get_serverRelativeUrl().split(listItemEnumerator.get_current().get_name())[0]
                            neurl = neurl + vPrefix + listItemEnumerator.get_current().get_name();
                            var myFile = context.get_web().getFileByServerRelativeUrl(fileUrl);
                            myFile.moveTo(neurl);
                            context.load(myFile);
                            context.executeQueryAsync(function (sender, args) {
                                console.log('We renamed the file. YAY! ')
                            },
                    function (sender, args) {
                        console.log('BOO!, We did not move the file. .')
                    });
                        }
                    },
                   function (sender, args) {
                   });
                }
                catch (err) {
                    alert(err);
                }
            },
              function (data, args) {
                  console.log(args);
              });
        });
    }

    </script>
</head>
<body>   
    Folder Name : <input id="txtFolder" type="text" value="testFolder" />
    Prefix : <input id="txtPrefix" type="text" value="Prefix" />
    <input type="button" value="Click me" onclick="fileRenameChange();" />
</body>
</html>

No comments:

Post a Comment