<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.