List and Library rename the file on upload

Hi,

I am using list and library control to upload files to a document library. All works good except, if I upload a new file and if the file name already exists in the SharePoint document library it will overwrite the existing one.

Is there any way we can add an ID of the lookup column on file upload event?

Hello @Rinu,

Are you renaming the file when it is uploaded to the library?

Have you followed the instructions from Update properties of uploaded files article?

Hi Mnikitina,

Thanks for the link, I was able to rename the file names with the below code. But i was having trouble renaming the filename with Id of the files uploaded?.

my intention is to append an ID to the uploaded file name something like below.

Filename_ID.fileExtention

Please see my code below

var listOrLibrary = 'SPDataTable1';
var docLibraryTitle = 'fileUploadListTest';
var docLibraryId = '32398E41-12E4-4E25-8618-670FB69362C7';

 var extension;
 var filename;
fd.spRendered(function() {
    fd.control(listOrLibrary).$on('filesUploaded',
        function(itemIds) {
            //get document library by Title
            var library = pnp.sp.web.lists.getById(docLibraryId);
            //go through each uploaded Item Id and set field values
            library.getListItemEntityTypeFullName().then(function(entityTypeFullName){

                var batch = pnp.sp.web.createBatch();
                var currentName;
                var uri;
               

                for(var i = 0; i < itemIds.length; i++){
                    //specify which fields to update and how
                    library.items.getById(itemIds[i]).inBatch(batch).update({Title: fd.field('Title').value}, "*", entityTypeFullName);
                   
                    library.items.getById(itemIds[i]).select('FileRef').get().then(function(item){
					uri = item.FileRef;
					extension = uri.substring(uri.lastIndexOf("."));
                    filename = uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf("."));
                    alert(filename);
                    alert(extension);
                    
                     });
                   library.items.getById(itemIds[i]).inBatch(batch).update({FileLeafRef: filename + '_' +  extension}, "*", entityTypeFullName);
                    
                
                }

                batch.execute().then(function(){
                    fd.control(listOrLibrary).refresh();
                });
            });
        });
});

Hello @Rinu,

Please try out the code below.

var listOrLibrary = 'SPDataTable1';
var docLibraryTitle = 'fileUploadListTest';
var docLibraryId = '32398E41-12E4-4E25-8618-670FB69362C7';

 var extension;
 var filename;
fd.spRendered(function() {
    fd.control(listOrLibrary).$on('filesUploaded',
        function(itemIds) {
            //get document library by Title
            var library = pnp.sp.web.lists.getById(docLibraryId);
            //go through each uploaded Item Id and set field values
            library.getListItemEntityTypeFullName().then(function(entityTypeFullName){

                var batch = pnp.sp.web.createBatch();
                var currentName;
                var uri;
               

                for(var i = 0; i < itemIds.length; i++){
                    //specify which fields to update and how
                    var itemId = itemIds[i];
                    library.items.getById(itemId).inBatch(batch).update({Title: fd.field('Title').value}, "*", entityTypeFullName);
                    batch.execute();
                    
                    library.items.getById(itemId).select('FileRef', 'Id').get().then(function(item){
                        return item	
                    
                     }).then(function(item){
                         uri = item.FileRef;
                         var fileID  = item.Id;
					     filename = uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf(".")) + '_' + fileID;
                         var nbatch = pnp.sp.web.createBatch();
                         library.items.getById(fileID).inBatch(nbatch).update({FileLeafRef: filename}, "*", entityTypeFullName)
                            nbatch.execute().then(function(){
                                fd.control(listOrLibrary).refresh();
                            });
                     });
                   }
            });
        });
});

Thank you Mnikitina, This worked as expected.

1 Like

@Margo - thank you for sharing this post with me. I have tried a few variations and am honestly lost.

I created a PA Flow that does the following. If I could accomplish the rename in Plumsail and turn off the flow, that is ideal.

Child Document Library Field Details

  • OrigName = the original file as uploaded by the user
    • The PA Flow copies the Name value at upload and writes it to this Single Line text field so we have a "before" name for comparison
  • Name = SharePoint built-in column
    • Once the two fields (DxMediaStem and BodySiteStem) have values manually selected by the user AFTER upload, the PA Flow concatenates DxMediaStem+ BodySiteStem+ RAND(1000,9999) and renames the file
  • DxMediaStem = Choice value manually selected by the user AFTER upload, but still in parent Plumsail form; the user cannot save the parent form until providing a value for this field
  • BodySiteStem = Choice value manually selected by the user AFTER upload, but still in parent Plumsail form; the user cannot save the parent form until providing a value for this field

GOALS

  • Rename Name field on UPLOAD with values from two fields (plus a random string) once they have content.
  • Capture the original file Name and write to another field for comparison

CODE ATTEMPTED


fd.spRendered(function() {

            var listOrLibrary = 'Private';
            var docLibraryTitle = 'Private';
            var docLibraryId = 'Private';
            var extension;
            var DxMediaStemV = fd.field('DxMediaStem').value;
            var BodySiteStemV = fd.field('BodySiteStem').value;
            var filename = "DxMediaStemV" + "BodySiteStemV";

fd.control(listOrLibrary).$on('filesUploaded',
        function(itemIds) {
            
            //get document library by Id
            var library = pnp.sp.web.lists.getById(docLibraryId);
            
            
            
            //get document library by Title
            //var library = pnp.sp.web.lists.getByTitle(docLibraryTitle);

                        
            //go through each uploaded Item Id and set field values
            library.getListItemEntityTypeFullName().then(function(entityTypeFullName){

            var batch = pnp.sp.web.createBatch();
            var currentName;
            var uri;

            for(var i = 0; i < itemIds.length; i++){

            //specify which fields to update and how
            var itemId = itemIds[i];


   
            library.items.getById(itemId).inBatch(batch).update({Title: fd.field('Name').value}, "DxMediaStemV" + "BodySiteStemV", entityTypeFullName);
            batch.execute();
                    
            library.items.getById(itemId).select('FileRef', 'Id').get().then(function(item){
                        return item; 
                    
            }).then(function(item){
                         uri = item.FileRef;
                         var fileID  = item.Id;
                         filename = uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf(".")) + '_' + fileID;
                         var nbatch = pnp.sp.web.createBatch();
                         
                         library.items.getById(fileID).inBatch(nbatch).update({FileLeafRef: filename}, "DxMediaStemV" + "BodySiteStemV", entityTypeFullName);
                            nbatch.execute().then(function(){
                                fd.control(listOrLibrary).refresh();
                            });
                     });
                   }
            });
        });
      });

@shedev,

Are you getting any errors when running the code? Please share the screenshot.

@Margo

Sorry for the delayed response. I am not getting any errors, I had a few undefined issues via F12 review, I which I fixed, but everything else works.

CODE

fd.spRendered(function() {

    var listOrLibrary = 'Private';
    var docLibraryTitle = 'Private';
    var docLibraryId = 'Private';

    fd.control(listOrLibrary).$on('filesUploaded',
        function(itemIds) {
            //get document library by Title
            var library = pnp.sp.web.lists.getById(docLibraryId);
            //go through each uploaded Item Id and set field values
            library.getListItemEntityTypeFullName().then(function(entityTypeFullName){

                var batch = pnp.sp.web.createBatch();
                var currentName;
                var uri;
               

                for(var i = 0; i < itemIds.length; i++){
                    //specify which fields to update and how
                    var itemId = itemIds[i];
                    library.items.getById(itemId).inBatch(batch).update({Title: fd.field('FileLeafRef').value}, "*", entityTypeFullName);
                    batch.execute();
                    
                    library.items.getById(itemId).select('FileRef', 'Id').get().then(function(item){
                        return item; 
                    
                     }).then(function(item){
                         uri = item.FileRef;
                         var fileID  = item.Id;

    var MediaFileTypeV = fd.field('MediaFileType').LookupValue.value;
    var BodySiteV = fd.field('BodySite').LookupValue.value;
    var extension;
    var filename = MediaFileTypeV + BodySiteV;
                         
                         filename = uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf(".")) + '_' + fileID;
                         var nbatch = pnp.sp.web.createBatch();
                         library.items.getById(fileID).inBatch(nbatch).update({FileLeafRef: filename}, "*", entityTypeFullName);
                            nbatch.execute().then(function(){
                                fd.control(listOrLibrary).refresh();
                            });
                     });
                   }
            });
        });
});

RESULT
After upload, when visiting the Document Library, the name is not changed.

NotRenaming

Hello @shedev ,

I am not sure if this can help you, but I have custom field where people can fill in whatever they want and then I rename the document based on their input in the form. Maybe this piece of code can help you :slight_smile:

  const validateDataInForm = async () => {
    const documentName = fd.field("FileLeafRef");
    const processGroup = fd.field("processGroup ");
    const plants= fd.field("plants");
    //////////////////////////////////////////////////////////////////
    const checkValueProcessGroup = checkDataInField(processGroup );
    const checkValuePlants = checkDataInField(plants);
    if (checkValueProcessGroup && checkValuePlants) {
      const processGrouPrefix = checkValueProcessGroup.name.split(" ")[0];
      const plantsPrefix = checkValuePlants.map((plant) => plant.name);
      const plantsPrefixJoined = plantsPrefix.join("_");
      // fd.field("FileLeafRef").value = documentPrefix;
      const itemId = fd.itemId;

      const item = await sp.web.lists
        .getById(workingLibraryId)
        .items.getById(itemId)
        .select("FileRef", "FileLeafRef")();
      const documentPrefix = `${processGrouPrefix} ${plantsPrefixJoined} ${handbookDocumentName.value}${documentName.$data._fileExtension}`;
      fd.field("FileLeafRef").$data.value = "";
      fd.field("FileLeafRef").$data.value = documentPrefix;
      fd.save();
    } else {
      return false;
    }
  };

Regards
Stepan

@StepanS - thank you very much. I am heading out the door but wanted to thank you and let you know I will review and try it out. Very very appreciated.

1 Like

Quick update @StepanS. I tried to adapt your code to my scenario and failed. User error probably but don't have the time this morning to hammer on it more than the 20 minutes already spent. I have some deadlines to meet and will take it up again.

Mostly, the code, when merged within my existing function is syntactically unstable. JSHINT is such a great tool and it was not impressed with what I gave it to check!

I have a few related posts talking about this issue. List or Library Control Buttons & Icons shows a short clip of what I need the control to do.

Thank you again for taking the time to give me some ideas to try. The Plumsail community far surpasses any Microsoft support as the users are helping users here. That matters, I think!

Hello @shedev,

The code you've shared has incorrect lines.

This must be list id that you can get from the List Settings page URL:

var docLibraryId = 'Private';

This code is invalid:

var MediaFileTypeV = fd.field('MediaFileType').LookupValue.value;
    var BodySiteV = fd.field('BodySite').LookupValue.value;

To get the display value of the lookup field, you must use this code:

fd.field('Field1').value.LookupValue;

And you need to set the filename variable only once. Remove this line:

filename = uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf(".")) + '_' + fileID;

Please see PnPjs documentation for more information and code examples.

I have obscured these for purposes of posting to the community, for security reasons, but I do have those values defined in my code. :slight_smile:

As for the other two comments, I will look again at examples and my code. I can't believe I transposed the value.LookupValue! I must have been tired - or staring at the same code too long. Geeze! Thank you as always.

1 Like