function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sukanta Anbu 7sukanta Anbu 7 

how to get the file name from the uploaded file or the selected file dynamically using jscript

I am trying to get the filename from the selected file or the uploaded file dynamically rather than saving the file in a given name. Here is my aura component and jsccript file. Please help me in getting the file name dynamically from the selected file.
The following is my component:

<aura:component controller="dmsDynamicUpload" implements="force:appHostable,lightning:availableForFlowScreens,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
        <!-- Attributes and Handler -->
        <aura:attribute name="message" type="String"/>
        <aura:attribute name="recordId" type="String"/>
         <aura:attribute name="fileName" type="String"/>       
        <!-- Comp -->
        <lightning:card title='Demo Upload' iconName="standard:lead">
            <div style="height:300px; width:500px;" >

                <div class="slds-grid slds-m-around--small slds-hide" style="height:100px; width:200px;" >
                    <input aura:id="file" type="file" name="file"></input>
                </div>
                <hr/>
                <div class="slds-grid slds-m-around--small" style="width:400px;">
                    <lightning:button class="upload slds-col--padded slds-size--1-of-1 slds-p-vertical_small" variant="neutral" label="Upload" onclick="{!c.click}">
                        <lightning:icon iconName="utility:touch_action" variant="inverse"/>
                    </lightning:button>
                </div>
                <div class="slds-align_absolute-center slds-grid slds-m-around--small slds-box slds-theme--default slds-hide" aura:id="previewContainer">
                    <img aura:id="imagePreview" class="imagePreview" src="{!$Resource.leadPreview}" height="500" width="450"/>
                </div>
                <br/>        
            </div>
        </lightning:card>
        
        
        <div style="border:1px solid #ccc">
            <lightning:button aura:id="submit" type="button" class="submit" onclick="{!c.submit}">Submit</lightning:button>
        </div>
        <b style="padding-top:10px;">File: {! v.fileName }</b>
        
</aura:component>

The following is my jscript file:

({
    submit : function(component, event, helper) {
        
        var fileInput  = component.find("file").getElement();
        var file = fileInput.files[0];
        console.log('file is coming==>'+file);

        var reader = new FileReader();
   
        reader.onload = function (e) {
            var fileContent = reader.result;
            var base64 = 'base64,';
            var dataStart = fileContent.indexOf(base64) + base64.length;
            fileContent = fileContent.substring(dataStart)
            console.log(fileContent);
            
            var fileName = component.get("v.fileName");
            var recordId = component.get("v.recordId");
            
            var action = component.get("c.POST");
            action.setParams({ file : fileContent, recordId : recordId });
             action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
            $A.enqueueAction(action);
        };
        reader.readAsDataURL(file);
        
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            mode: 'sticky',
            message: 'Success',
            messageTemplate: '{0} record created! See it {1}!',
            messageTemplateData: ['Job', {
                url: 'https://csv-file-upload.herokuapp.com/leads/' + recordId,
                label: 'here',
                }
            ]
        });
        toastEvent.fire();
    },
    click : function(component, event, helper) {
        
        var input = component.find("file").getElement();
        input.click();
        
        var action = component.get("c.createJob");
        action.setCallback(this, function(response) {
            
                var returnValue = response.getReturnValue();
                console.log(returnValue);
                
                component.set("v.recordId", returnValue[0]);
                component.set("v.fileName", returnValue[1]);
                
            });
            $A.enqueueAction(action);
        
        window.setTimeout(
            $A.getCallback(function() {
                $A.util.removeClass(component.find('previewContainer'),"slds-hide");
            }), 120000
        )
    },
})
Best Answer chosen by sukanta Anbu 7
David Zhu 🔥David Zhu 🔥
You may make changes to you code as below:
1. in HTML, Use lightning:input compnent to replace this line: <div class="slds-grid slds-m-around--small slds-hide" style="height:100px; width:200px;" >
                    <input aura:id="file" type="file" name="file"></input>
                </div>
To 
<lightning:input aura:id="file" name="file" type="file" label="Attachment" required="true" multiple="false" onchange="{! c.handleFilesChange}"/>

2. Add js controller function handleFilesChange
    handleFilesChange : function(component, event, helper) {
        let files = event.getSource().get("v.files");
        let fileName = files[0].name;
        component.set("v.fileName", fileName);
    },