3

We allow our users to upload pictures to a particular salesforce record using their phones. Before saving the file in salesforce, we would like to send out the picture to our servers to perform some transformations and then save the transformed picture to salesforce. So we need a way to capture the blob of the selected picture. Do you have any idea how to accomplish this?

We are using the below code to upload files:

<aura:component implements="force:lightningQuickAction">
    <aura:attribute name="accept" type="List" default="['.jpg', '.jpeg']"/>
    <aura:attribute name="multiple" type="Boolean" default="true"/>
    <aura:attribute name="disabled" type="Boolean" default="false"/>

    <lightning:fileUpload  name="fileUploader"
                           label= "Upload Picture"
                           multiple="{!v.multiple}"
                           accept="{!v.accept}"
                           disabled="{!v.disabled}"
                           recordId="a0u8E000003H1ueQAC"
</aura:component>
4

You handle the onchange event on your fileuploader component, extract the value and convert to binary string to send.

Component:

<lightning:input type="file" files="{!v.fileList}" label="Upload Files" name="file" multiple="true" onchange="{!c.handleFilesChange}"/>

Controller:

handleFilesChange : function(component, event){
  var firstFile = event.getSource().get("v.files")[0];
  var reader = new FileReader();
  var base64DataURL;
  var base64File;

  reader.onload = $A.getCallback(function() {
    //remove the bit at the start 'base64, ' if necessary
    var base64DataURL = objFileReader.result;
    var base64 = 'base64,';
    var fileStart = base64DataURL.indexOf(base64) + base64.length;

    base64File = base64DataURL.substring(fileStart);

  });
  reader.readAsDataURL(firstFile);
}    

You can also read the files these ways:

//returns a binary string
var binaryFile = reader.readAsBinaryString(firstFile);

//returns a text string
var textFile = reader.readAsText(firstFile);

//returns and ArrayBuffer
var arrBufferFile = reader.readAsArrayBuffer(firstFile);
| improve this answer | |
  • Nice, thank you very much. I was hoping that I could get the blob using the lightning:fileUpload because I want process bar, but I guess that with your solution I can also include a progress bar. – Cuban coffee Nov 27 '19 at 5:31
  • Yes, to get the binary data out of the file, you can then query the contentdocument, but it's a bit of a hassle. – Caspar Harmer Nov 27 '19 at 17:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.