简体   繁体   中英

Unable to read and upload file using FileReader object in Lightning component

I am trying to upload a file into Salesforce using the Lightning input component:

Component

<aura:component controller="FileUploadController">

<lightning:input 
    aura:id="fileId" 
    onchange="{!c.readFile}" 
    type="file" 
    name="file" 
    multiple="false"/>

</aura:component>

Controller

({
    readFile : function(component) {
        var file = component.find("fileId").get("v.files")[0];
        var reader  = new FileReader();

        reader.onload = function(e) {
            var fileContent = e.target.result;
            var base64 = 'base64,';
            var dataStart = fileContent.indexOf(base64) + base64.length;

            fileContent = fileContent.substring(dataStart);
            uploadFile(file, fileContent, component);
        }
        reader.readAsDataURL(file); 
    },

    uploadFile : function(file, fileContent, component) {
        var action = component.get("c.createFile"); 

        action.setParams({
            fileName: file.name,
            base64Data: encodeURIComponent(fileContent)
        });

        $A.enqueueAction(action);
    }
})

The issue I am having is I am unable to get uploadFile() to be called from readFile(). Any suggestions would be great. Thank you.

I ended up moving the uploadFile method to a helper class and that resolved the issue:

Component

<aura:component controller="FileUploadController">

<lightning:input 
    aura:id="fileId" 
    onchange="{!c.readFile}" 
    type="file" 
    name="file" 
    multiple="false"/>

</aura:component>

Controller

({
    readFile : function(component, event, helper) {
        var file = component.find("fileId").get("v.files")[0];
        var reader  = new FileReader();

        reader.onload = function() {
            var fileContent = reader.result;
            var base64 = 'base64,';
            var dataStart = fileContent.indexOf(base64) + base64.length;

            fileContent = fileContent.substring(dataStart);
            helper.uploadFile(component, fileContent, file);
        }
        reader.readAsDataURL(file); 
    }
})

Helper

({
    uploadFile : function(component, fileContent, file) {
        var action = component.get("c.createFile"); 

        action.setParams({
            fileName: file.name,
            base64Data: encodeURIComponent(fileContent)
        });

        $A.enqueueAction(action);

        $A.get("e.force:closeQuickAction").fire();
    }
})

For FileReader to read contents of file correctly such as Word documents and Excel sheets, the ContentType may also have to be specified :- The controller class :

public class SagarAttachFile {

    public String fileName {get;set;}
    public String fileValue {get;set;}
    public String contentType {get;set;}

    public Attachment attachment {
        get {
            if(attachment == null)
                attachment = new Attachment();
            return attachment;
        }
        set;
    }

    public SagarAttachFile()
    {
        fileName = '';
        fileValue = '';
        contentType = '';
    }

    public PageReference saveMethod()
    {
        if(attachment != null && fileName != null && fileName != ''
            && fileValue != null && fileValue != '')
        {        
            try
            {
                attachment.ownerId = UserInfo.getUserId();
                attachment.ParentId = '5002C000006zvjyQAA'; // Attach the uploaded file as an attachment to this Case.
                attachment.Name = fileName;

                fileValue = EncodingUtil.urlDecode(fileValue, 'UTF-8');
                attachment.Body = EncodingUtil.base64Decode(fileValue);
                attachment.ContentType = contentType;

                insert attachment;
            }
            catch (DMLException e) {
                System.debug(LoggingLevel.INFO, '#### error occurred while adding attachment to case ' + e.getMessage());
            }
            finally
            {
                attachment = new Attachment(); 
            }
        }
        else
        {
            System.debug(LoggingLevel.INFO, '#### no attachment adding to case');
        }
        return null;
    }           
  }

The Visualforce page :

<apex:page controller="SagarAttachFile">
    <apex:form>
        <apex:actionFunction name="saveAF" action="{!saveMethod}" reRender="attchFilePanel">
            <apex:param assignTo="{!fileName}" value="" name="fileName"/>
            <apex:param assignTo="{!fileValue}" value="" name="fileValue"/>
            <apex:param assignTo="{!contentType}" value="" name="contentType"/>
        </apex:actionFunction>
        <apex:pageBlock id="pageBlock1">
            <apex:outputPanel id="attchFilePanel">
                <input type="file" id="file" name="attFile"/>
                <apex:commandButton value="Save" onclick="javascriptFunc1(); return false;"/>
            </apex:outputPanel>
        </apex:pageBlock>
    </apex:form>
    <script>
    function javascriptFunc1()
    {
        var fileName = null;
        var file1 = document.getElementById('file');   
        if(file1 != null)
        {
            if ('files' in file1)
            {
                if (file1.files.length == 1)
                {
                    alert('one file attached');
                    var file1Obj = file1.files[0];                           
                    if(file1Obj.name != '')
                    {
                        fileName = file1Obj.name;
                    }
                    var reader = new FileReader();
                    reader.onload = function() {
                        alert('reading is done now');
                        var fileContent = reader.result;
                        var base64 = 'base64,';
                        var dataStart = fileContent.indexOf(base64) + base64.length;
                        fileContent = fileContent.substring(dataStart);
                        var encodedFileContent = encodeURIComponent(fileContent);
                        saveAF(fileName, encodedFileContent, file1Obj.type);                        
                    }
                    reader.readAsDataURL(file1Obj);    
                }
                else
                {
                    alert('no file attached');    
                }
            }    
        }
    }
    </script>
</apex:page>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM