2

I want to attach the file on save of the record

It works well in Desktop. Record gets saved and attachment is also saved under that record. But in mobile-only record is saved attachment server side controller is not called.

id desktop I can track all console logs but in Salesforce 1 last part that is "--state--" this log is not traced

here is the code

Parent Component

<aura:attribute name="parentId" type="String" />
<c:fileUpload aura:id="file_Upload" parentId="{!v.parentId}"/> 

<button class="slds-button slds-button_brand"  onclick="{!c.save}">Save</button>

Parent Controller

saveRecord : function(component,from ) {
        var action = component.get("c.saveExpWrap");
         action.setParams({
            "expWrapperJSON": JSON.stringify(expWrap)
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            console.log(state);
            console.log('response-->'+response);
            if (state === "SUCCESS") {
                var recId = response.getReturnValue()+'';
                component.set("v.parentId",recId);
                var childComponent = component.find("file_Upload");
                childComponent.getSaveFile(action);
            }else if(state === "ERROR"){
                alert('Error Occured!!');
            }
        });
        $A.enqueueAction(action);
    }

FileUpload.cmp

<aura:component controller="VR_Interface_Controller">
 <!-- 'parentId' Aura Attribute for store the Id for Parent Record where we are attach our file -->  
   <aura:attribute name="parentId" type="Id" default="" />
 <!-- 'showLoadingSpinner' attribute for show/hide the uploading image and msg in aura:if-->
   <aura:attribute name="showLoadingSpinner" type="boolean" default="false" />
 <!-- 'fileName' attribute for display the selected file name -->  
   <aura:attribute name="fileName" type="String" default="No File Selected.." />
 <!-- Lightning Input with file type and on file change call the 'handleFilesChange' controller --> 

    <aura:method name="getSaveFile" action="{!c.doSave}" access="PUBLIC"/>

   <lightning:input aura:id="fileId" onchange="{!c.handleFilesChange}" type="file" name="file" label="Upload Attachment" multiple="false"/>
   <div class="slds-text-body_small slds-text-color_error">{!v.fileName} </div>

 <!--use aura:if for show-hide the loading spinner image--> 
   <aura:if isTrue="{!v.showLoadingSpinner}">
      <div class="slds-text-body_small slds-text-color_error">Uploading... 
         <img src="/auraFW/resources/aura/images/spinner.gif" class="spinner-img" alt="Loading"/>'
      </div>
   </aura:if>

 <br/>

<!--    <button class="slds-button slds-button_brand" onclick="{!c.doSave}">Upload Attachment</button> -->
</aura:component>

FileUpload.controller

({
    doSave: function(component, event, helper) {
        console.log('doSave Parent---->'+component.get("v.parentId"));
        if (component.find("fileId").get("v.files").length > 0) {
            helper.uploadHelper(component, event);
        } else {
            alert('Please Select a Valid File');
        }
    },

    handleFilesChange: function(component, event, helper) {
        var fileName = 'No File Selected..';
        if (event.getSource().get("v.files").length > 0) {
            fileName = event.getSource().get("v.files")[0]['name'];
        }
        component.set("v.fileName", fileName);
    },
})

FileUpload.helper

({
    MAX_FILE_SIZE: 4500000, //Max file size 4.5 MB 
    CHUNK_SIZE: 750000,      //Chunk Max size 750Kb 

    uploadHelper: function(component, event) {
        // start/show the loading spinner   
        component.set("v.showLoadingSpinner", true);
        // get the selected files using aura:id [return array of files]
        var fileInput = component.find("fileId").get("v.files");
        // get the first file using array index[0]  
        var file = fileInput[0];
        var self = this;
        // check the selected file size, if select file size greter then MAX_FILE_SIZE,
        // then show a alert msg to user,hide the loading spinner and return from function  
        if (file.size > self.MAX_FILE_SIZE) {
            component.set("v.showLoadingSpinner", false);
            component.set("v.fileName", 'Alert : File size cannot exceed ' + self.MAX_FILE_SIZE + ' bytes.\n' + ' Selected file size: ' + file.size);
            return;
        }

        // create a FileReader object 
        var objFileReader = new FileReader();
        // set onload function of FileReader object   
        objFileReader.onload = $A.getCallback(function() {
            var fileContents = objFileReader.result;
            var base64 = 'base64,';
            var dataStart = fileContents.indexOf(base64) + base64.length;

            fileContents = fileContents.substring(dataStart);
            // call the uploadProcess method 
            self.uploadProcess(component, file, fileContents);
        });

        objFileReader.readAsDataURL(file);
    },

    uploadProcess: function(component, file, fileContents) {
        // set a default size or startpostiton as 0
        console.log('--uploadProcess--'); 
        var startPosition = 0;
        // calculate the end size or endPostion using Math.min() function which is return the min. value   
        var endPosition = Math.min(fileContents.length, startPosition + this.CHUNK_SIZE);

        // start with the initial chunk, and set the attachId(last parameter)is null in begin
        this.uploadInChunk(component, file, fileContents, startPosition, endPosition, '');
    },


    uploadInChunk: function(component, file, fileContents, startPosition, endPosition, attachId) {
        // call the apex method 'saveChunk'
        var getchunk = fileContents.substring(startPosition, endPosition);
        var action = component.get("c.saveChunk");
        action.setParams({
            parentId: component.get("v.parentId"),
            fileName: file.name,
            base64Data: encodeURIComponent(getchunk),
            contentType: file.type,
            fileId: attachId
        });
        console.log('--uploadInChunk--'+action);
        console.log('--parentId--'+component.get("v.parentId"));
         console.log('--fileName--'+file.name);
        console.log('--base64Data--'+encodeURIComponent(getchunk));
        console.log('--contentType--'+file.type);
        console.log('--fileId--'+attachId);
        // set call back 
        action.setCallback(this, function(response) {
            // store the response / Attachment Id   
            attachId = response.getReturnValue();
            var state = response.getState();
            console.log( attachId +'--state--'+state);
            if (state === "SUCCESS") {
                // update the start position with end postion
                startPosition = endPosition;
                endPosition = Math.min(fileContents.length, startPosition + this.CHUNK_SIZE);
                // check if the start postion is still less then end postion 
                // then call again 'uploadInChunk' method , 
                // else, diaply alert msg and hide the loading spinner
                if (startPosition < endPosition) {
                    this.uploadInChunk(component, file, fileContents, startPosition, endPosition, attachId);
                } else {
                    alert('your File is uploaded successfully');
                    component.set("v.showLoadingSpinner", false);
                }
                // handel the response errors        
            } else if (state === "INCOMPLETE") {
                alert("From server: " + response.getReturnValue());
            } else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });
        console.log('--end of upload--');
        // enqueue the action
        $A.enqueueAction(action);
    }
})
2
  • so, no ERROR or SUCCESS state? any server side logs? – glls Mar 26 '18 at 15:10
  • yes. no error or success – SFDC shaikh Mar 26 '18 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.