upload file using lightning sfdmconkey

Custom File Upload In Salesforce Lightning Component – Upload Large Attachments

Lightning Component

Hey Guys,

Today in this post we are going to learn about how to create a custom file upload salesforce lightning component. This post inspire and new updated version of ‘Peter Knolle‘ post ‘upload file component’.

For this post we are using the chunk file upload method, by this chunk file upload method we can upload large file attachments within the heap size limitation, we are using the small 750kb chunks for upload our attachment.

Using this sample code you can upload attachments upto 4.5 Mb.
Lightning Component Output Sample : 

upload file using lightning sfdmconkey

Now let’s start code …

Step 1 : Create Apex Controller : FileUploadController.apxc

From Developer Console >> File >> New >> Apex Class

  • see code comments.
Step 2 : Create Lightning Component: fileUpload.cmp 

From Developer Console >> File >> New >> Lightning Component

  • In the above lightning component on line number 10, we have a attribute called ‘parentId’ , in this attribute you have need to set the parent id, in in sample i am using the account id.
  • see code comments.

you can select or drag your file in this lightning component

JavaScript Controller : fileUploadController.js

JavaScript Helper : fileUploadHelper.js

  • see code comments.
From developer console >> file >> new >> Lightning Application
demo.app [Lightning Application]

Output:

upload file using lightning sfdmconkey

Related Resource:

Like our facebook page for new post updates. & Don’t forget to bookmark this site for your future reference.

if you have any suggestions or issue with it, you can share your thoughts  in comment box.

Happy Learning 🙂

(Visited 36,763 times, 1 visits today)

49 comments

  • Hi Friends,

    I have one doubt, I am using document object for profile pictures it is not allowing more than 1 Mb file in side the Salesforce. I want to increase capacity from 1 Mb to 4 Mb please tell how can I achieve that.

    Here given below link which I am using for picture upload.

    https://developer.salesforce.com/blogs/developer-relations/2015/11/create-lightning-component-drag-drop-profile-pictures.html

     

    Please help me where I need to do changes for 4 Mb file uploading

     

    Thanks in Advance.

     

    Regards,

    Rajesh

     

  • Hi Team,

    What is the maximum file size that we can upload?

    I have tried and observed that we can upload only maximum of 4.5MB file, As there is an exception being thrown from apex i.e. Heap Exception on string value is crossing 6MB.

    Is there any other alternative way that we can upload file of more than 5MB?

     

     

  • Absolutly right. From Apex you can upload only 4.5 Mb attachments. It depends on heap size limit for String class (6Mb). Because we using base64 encoding we will take only 6*0.75=4.5Mb. But If you can upload file from 3-party server this size will grow. I want tell about Rest API. For Attachment limit is 25Mb. If you choise Document you can upload up to 2Gb. If you choise other Object with Blob field it is only 500Mb.

  • Hi Guys,

    The above code is not working for me. I mean it is not throwing any exception at the same time all the time the spinner is rendering and attachment also not get created in Salesforce.

    Please let me know. Thanks!

  • Hi Team,

    The above code is not working for me. When I have upload a image all the time spinner is rendering and image also not inserting in side the salesforce. Please let me know. Thanks!

    • Update the ParentId from the code above to the object ID to which you want to save the attachment and it should work. Thanks.

  • Hi Everyone,

    Can you help me to use this component to upload attachment before saving the record.
    The scenario is the user has to upload the document while creating the record.

  • I updated all classes from parentId to caseId. But i get an error on line 27 “Variable does not exist: caseId”

  • How can I pass a flow variable into the controller where you have hard coded the account id? Please help me, I am stuck at this point.

  • Hi Piyush,

     

    Could you please help me, I want to replace parentId with the dynamic caseid from my flow. How can I accomplish this to pass flow output variable to this lightning component.

     

    Regards

    Chetan Bhatla

     

    • I got it working, getting a flow variable into this lighning component. Thanks for this amazing article. this solved my problem of attaching a file with the case by community guest user who does not have Edit access on case object.

      Thanks Again.

  • Hello,

    You can include a attribute called as accept in the lightning:input tag. By this way you can restrict the types of attachments that can be uploaded. Also you can specify if you need to access the camera on a smatrphone or a tablet using the salesforce1 app or also if salesforce is opened from a mobile browser. This is a very good use case for service engineers to capture images on the go and upload it to any record.

     

  •  private static void appendToFile(Id fileId, String base64Data) {
            base64Data = EncodingUtil.urlDecode(base64Data, ‘UTF-8’);

            Attachment a = [
                SELECT Id, Body
                FROM Attachment
                WHERE Id =: fileId
            ];

            String existingBody = EncodingUtil.base64Encode(a.Body);

            a.Body = EncodingUtil.base64Decode(existingBody + base64Data);

            update a;
        }
     hi piyush i need test class for this method could you please provide if possible…thanks

  • Hi ,

    I am using the above code to save attachment.After inserting it is returning attachment but when i query the record with the returned Id it is giving me zero results.FileId is not null.
    Attachment a = [
    SELECT Id, Body
    FROM Attachment
    WHERE Id =: fileId
    ];

    Can you please let me know if it is still pending or why is it returning zero results?

    Thanks

  • Hi ,
    I am using the above code. After inserting attachment it is returning Id, but when I fetch the record by SOQL query it is returning me no records.
    Attachment a = [
    SELECT Id, Body
    FROM Attachment
    WHERE Id =: fileId
    ];

    Can you please let me know why is it returning zero records?Is it still pending for insertion

  • Hi Piush,

    This code worked for me, but only upto 4.5MB files are uploading. Is there any way to upload bigger files like (10-25MB) files.

     

    Thanks

  • Hi Piush,

    This code worked for me, but only upto 4.5 files are uploading is there any way to upload bigger files like (10-20MB) files.

     

    Thanks

  • Hi Piyush,

    I want to have the same kind of functionality but i want to save the browsed image to document object.how can i do that?

  • Hi Piyush,

    your checking the file size in helper.it is not working properly
     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;
            }
    here i want restrict the file size is 3mb.its not working properly.
     

  • Can this code work for standalone lightning component?

    I have registeration form,i need to attach resume upload functionality to it. But your code doesnt work , as it keep spinnng and file never saves.

  • Hi. Piyush,,

    Im using the above code and created custom case componets but im unable to attch files morethen 2 Mb Pdf or ther files. Spinner shoulf be loading after 2MB files loaded. It works fime for small files below 1. 5 Mb. How can it work for others to uplaod upto 4.5 Mb. Any one tell me plz…. And ho can we increase upto 10 mb

     

     

    Thank you

    Emran

  • HI, Piyush

    by using this code im unable to upload file more then 1.5 mb, but you said limit is 4.5 mb, if i upload filesize morethen 2mb spinner should loading and file not attached, the debug log says apex heap size limit is more then the limit. how can we resolve this issue. pls update me

     

     

     

    Thank you

     

    emran

     

  • Hi Guys not sure if any one Still needs Test Class for the Above Apex class:

    @IsTest
    private class OppImplementationService_UploadFileTest {

    static testMethod void testAttachmentsWithOutFile(){

    Account testAccount1 = buildAccount(‘TestAccount’);
    Insert testAccount1;

    Opportunity testOpportunity1 = buildOpportunity(‘Stage 0 – Prospect’,’test Opportunity’,testAccount1.Id);
    Insert testOpportunity1;

    UploadFile handler = new UploadFile();
    String fileName = ‘Test Attachment’;
    String filebody =’Hi this is the test Attachment to Upload’;
    Blob beforeblob = Blob.valueOf(filebody);
    string paramvalue = EncodingUtil.base64Encode(beforeblob);
    String contentType =’text/plain’;
    String fileId =”;
    Id attachmentCreatedFileId = UploadFile.saveChunk(testOpportunity1.Id,fileName,paramvalue,contentType,fileId);
    UploadFile.saveChunk(testOpportunity1.Id,fileName,paramvalue,contentType,attachmentCreatedFileId);

    List<Attachment> attachments=[select id, name from Attachment where parent.id=:testOpportunity1.id];
    System.assertEquals(1, attachments.size());
    }

    public Static Account buildAccount(String accName){
    Account testAccount = new Account();
    testAccount.Name = accName;

    //All the mandatory Fields

    return testAccount;
    }

    public Static Opportunity buildOpportunity(String oppStageName, String oppName, id oppAccountId){
    Opportunity testopportunity = new Opportunity();
    testopportunity.StageName = oppStageName;
    testopportunity.Name = oppName;
    testopportunity.closeDate = system.today()+20;
    testopportunity.Amount = 20000;
    testopportunity.AccountId = oppAccountId;
    // All the mandatory Fields

    return testopportunity;
    }
    }

    Hope the test Class will be help full.

     

     

  • How to do this for Document object in salesforce.  Eg I want to upload PDF files  in Document object with specified document folder names. Please help me with this

Leave a Reply