Tuesday, August 1, 2017

Lightning Component for attaching files using input file component

A rough markup of this component using input type file component. Please refer the previous article to get an idea of how the helper JS and the apex class is formed.

<div class="slds-form-element">
    <span class="slds-form-element__label" id="file-selector-id">Attachment</span>
    <div class="slds-form-element__control">
        <div class="slds-file-selector slds-file-selector_files">
            <div class="slds-file-selector__dropzone">
                <input type="file" class="slds-file-selector__input slds-assistive-text" accept="image/png" id="file-upload-input-01" aria-describedby="file-selector-id" aura:id="file" onchange="{!c.showfile}"/>
                <label class="slds-file-selector__body" for="file-upload-input-01">
                    <span class="slds-file-selector__button slds-button slds-button_neutral">
                        <c:svgIcon class="slds-button__icon slds-button__icon_left" xlinkHref="/resource/slds232/assets/icons/utility-sprite/svg/symbols.svg#upload" />
                        Upload Files
                    </span>
                    <span class="slds-file-selector__text slds-medium-show">or Drop Files</span>
                </label>
            </div>
        </div>
    </div>
</div>

showfile:function(component,event,helper){
    helper.show(component,event);
    
    var f = event.target.files[0]; 
    var fileInput = component.find("file").getElement();
    var file = fileInput.files[0];
    
    var reader = new FileReader();
    reader.onloadend = function(e) {
        var contents = e.target.result;
        var base64Mark = 'base64,';
        var dataStart = contents.indexOf(base64Mark) + base64Mark.length;
        var fileContents = contents.substring(dataStart);
        
        helper.upload(component, file, encodeURIComponent(fileContents), function(answer) {
            if (answer) {
                helper.hide(component,event);
            }
            else{
            }
        });
    }
    reader.readAsDataURL(file);
}

Share This:    Facebook Twitter

Lightning Component for attaching files using lightning:input


<aura:component description="FileUploader" controller="FileUploadController">
    <aura:attribute name="fileToBeUploaded" type="Object[]"/>
    <lightning:spinner aura:id="mySpinner" class="slds-hide"/>
    
    <div class=" slds-box">
        <div class="slds-grid slds-wrap">
            <lightning:input aura:id="file-input" type="file"
                             files="{!v.fileToBeUploaded}"
                             onchange="{!c.onFileUploaded}"
                             accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                             label="Attachment"
                             name="file" multiple="true"/>
        </div>
    </div>
</aura:component>

({
    onFileUploaded:function(component,event,helper){
        helper.show(component,event);
        var files = component.get("v.fileToBeUploaded");
        if (files && files.length > 0) {
            var file = files[0][0];
            var reader = new FileReader();
            reader.onloadend = function() {
                var dataURL = reader.result;
                var content = dataURL.match(/,(.*)$/)[1];
                helper.upload(component, file, content, function(answer) {
                    if (answer) {
                        helper.hide(component,event);
                        // Success
                    }
                    else{
                        // Failure
                    }
                });
            }
            reader.readAsDataURL(file);
        }
        else{
            helper.hide(component,event);
        }
    }
})

({
    upload: function(component, file, base64Data, callback) {
        var action = component.get("c.uploadFile");
        console.log('type: ' + file.type);
        action.setParams({
            fileName: file.name,
            base64Data: base64Data,
            contentType: file.type
        });
        action.setCallback(this, function(a) {
            var state = a.getState();
            if (state === "SUCCESS") {
                callback(a.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    show: function (cmp, event) {
        var spinner = cmp.find("mySpinner");
        $A.util.removeClass(spinner, "slds-hide");
        $A.util.addClass(spinner, "slds-show");
    },
    hide:function (cmp, event) {
        var spinner = cmp.find("mySpinner");
        $A.util.removeClass(spinner, "slds-show");
        $A.util.addClass(spinner, "slds-hide");
    }
})

public class FileUploadController {
    @AuraEnabled
    public static Id uploadFile(String fileName, String base64Data, String contentType) { 
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
        Attachment a = new Attachment();
        a.parentId = '0017F000007xoiVQAQ';
        a.Body = EncodingUtil.base64Decode(base64Data);
        a.Name = fileName;
        a.ContentType = contentType; 
        insert a;
        System.debug(a.Id);
        return a.Id;
    }
}

NOTE: For demo purpose, I have hardcoded the value of an account '0017F000007xoiVQAQ' in the apex class. In actual scenario, you should get this ID from the component.
Share This:    Facebook Twitter

Friday, July 21, 2017

Including SVG in a Lightning Component

This is a helper Lightning Component to render the Lightning Design System sprited icons.

1. Create svgIcon component.
<aura:component access="global">
  <aura:attribute name="class" type="String" access="global"/>
  <aura:attribute name="xlinkHref" type="String" access="global"/>
  <aura:attribute name="ariaHidden" type="String" default="true" access="global"/>
</aura:component>



({
    render: function(component, helper) {
        var classname = component.get("v.class");
        var xlinkhref = component.get("v.xlinkHref");
        var ariaHidden = component.get("v.ariaHidden");
        
        var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
        svg.setAttribute('class', classname);
        svg.setAttribute('aria-hidden', ariaHidden);
        svg.innerHTML = '<use xlink:href="'+xlinkhref+'"></use>';
        return svg;
    }
})

2. Upload the SLDS zip file as static resource.

3. Use this new component whenever you need an Lightning Design System SVG icon like below:
<c:svgIcon class="slds-icon slds-icon_x-small" xlinkHref="/resource/slds232/assets/icons/utility-sprite/svg/symbols.svg#user" />

Reference: https://www.lightningdesignsystem.com/resources/lightning-svg-icon-component-helper/
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top