({
doInit:function(component,event,helper){
var action = component.get("c.getFiles");
action.setParams({
"recordId":component.get("v.recordId")
});
action.setCallback(this,function(response){
var state = response.getState();
if(state=='SUCCESS'){
var result = response.getReturnValue();
console.log('result: ' +result);
component.set("v.files",result);
}
});
$A.enqueueAction(action);
} ,
//Open File onclick event
OpenFile :function(component,event,helper){
var rec_id = event.currentTarget.id;
$A.get('e.lightning:openFiles').fire({ //Lightning Openfiles event
recordIds: [rec_id] //file id
});
},
UploadFinished : function(component, event, helper) {
var uploadedFiles = event.getParam("files");
var documentId = uploadedFiles[0].documentId;
var fileName = uploadedFiles[0].name;
helper.UpdateDocument(component,event,documentId);
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Success!",
"message": "File "+fileName+" Uploaded successfully."
});
toastEvent.fire();
/* Open File after upload
$A.get('e.lightning:openFiles').fire({
recordIds: [documentId]
});*/
},
})
.js Helper:
({
UpdateDocument : function(component,event,Id) {
var action = component.get("c.UpdateFiles");
var fName = component.find("fileName").get("v.value");
//alert('File Name'+fName);
action.setParams({"documentId":Id,
"title": fName,
"recordId": component.get("v.recordId")
});
action.setCallback(this,function(response){
var state = response.getState();
if(state=='SUCCESS'){
var result = response.getReturnValue();
console.log('Result Returned: ' +result);
component.find("fileName").set("v.value", " ");
component.set("v.files",result);
}
});
$A.enqueueAction(action);
},
})
Apex Controller:
public class SimplyfyFilesCntrl {
@AuraEnabled
public static List<ContentDocument> getFiles(string recordId){
List<ContentDocument> DocumentList = new List<ContentDocument>();
Set<Id> documentIds = new Set<Id>(); //store file ids
List<ContentDocumentLink> cdl=[select id,LinkedEntityId,ContentDocumentId from ContentDocumentLink where LinkedEntityId=:recordId];
for(ContentDocumentLink cdLink:cdl){
documentIds.add(cdLink.ContentDocumentId); // Document ids
}
DocumentList = [select Id,Title,FileType,ContentSize,Description from ContentDocument where id IN: documentIds];
return DocumentList;
}
@AuraEnabled
public static List<ContentDocument> UpdateFiles(string documentId,string title,string recordId){
system.debug('title: ' +title);
ContentDocument cd = [select id,title from ContentDocument where Id=:documentId]; // Getting files from Parent record
cd.Title = title; // Changing file Title with user entered title
try{
update cd; // Update ContentDocument (File)
}
catch(DMLException e){
system.debug('Exception has occurred! ' +e.getMessage());
}
List<ContentDocument> DocumentList = new List<ContentDocument>();
Set<Id> documentIds = new Set<Id>();
List<ContentDocumentLink> cdl=[select id,LinkedEntityId,ContentDocumentId from ContentDocumentLink where LinkedEntityId=:recordId];
for(ContentDocumentLink cdLink:cdl){
documentIds.add(cdLink.ContentDocumentId);
}
DocumentList = [select Id,Title,FileType,ContentSize,Description from ContentDocument where id IN: documentIds];
return DocumentList; // Return list of files on parent record
}
}
Hi Nagaraju, Assume you want to upload attachment within an Account so enter an Account name and then upload an attachment with this Account. Try this code: Lightning Component : (UploadAttachment) <aura:component controller="FileUploadToController">
uploadHelper: function(component, event) { component.set("v.showLoadingSpinner", true); var fileInput = component.find("fileId").get("v.files"); // get the first file using array index[0] var file = fileInput[0]; var self = this; 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; }
var objFileReader = new FileReader(); objFileReader.onload = $A.getCallback(function() { var fileContents = objFileReader.result; var base64 = 'base64,'; var dataStart = fileContents.indexOf(base64) + base64.length;
return oAttachment.Id; } } Lightning Application: (UploadAttachmentApp) <aura:application extends="force:slds"> <c:UploadAttachment/> </aura:application> I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too. Thanks, Ajay Dubedi
If I want it to work on my custom object Feedback, then what to do. actually I have on Audio recorder there. I want to attach that recording in that Object's detail page.
.cmp File
.js Controller:
.js Helper:
Apex Controller:
If it's help you mark as Best Answere.
Thanks & regards,
Harsh P.
Assume you want to upload attachment within an Account so enter an Account name and then upload an attachment with this Account.
Try this code:
Lightning Component : (UploadAttachment)
<aura:component controller="FileUploadToController">
<aura:attribute name="AccountName" type="String" />
<lightning:input type="text" placeholder="Enter First Name"
aura:Id="accname" onblur = "{!c.accname}" />
<aura:attribute name="fileName" type="String" default="No File Selected.." />
<aura:attribute name="returnFileName" type="String" />
<div>
<lightning:input aura:id="fileId" onchange="{!c.handleFilesChange}" type="file" name="file" multiple="false" style="display: flex"/><br/>
<div class="slds-text-body_small slds-box" style="color:red;width: 200px;height: 23px">{!v.fileName} </div><br/>
</div>
<button class="slds-button slds-button_brand" onclick="{!c.doSave}">Upload Attachment</button>
</aura:component>
Controller:
({
doSave: function(component, event, helper) {
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);
},
accname : function(component, event, helper) {
var accname = component.find("accname");
var value = accname.get("v.value");
var letters = /^[A-Za-z]+$/;
if(value.match(letters))
{
console.log("--- > " + value);
component.set("v.AccountName", value);
return true;
}
else
{
component.set("v.AccountName", null);
return false;
}
},
})
Helper:
({
MAX_FILE_SIZE: 4500000, //Max file size 4.5 MB
CHUNK_SIZE: 750000, //Chunk Max size 750Kb
uploadHelper: function(component, event) {
component.set("v.showLoadingSpinner", true);
var fileInput = component.find("fileId").get("v.files");
// get the first file using array index[0]
var file = fileInput[0];
var self = this;
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;
}
var objFileReader = new FileReader();
objFileReader.onload = $A.getCallback(function() {
var fileContents = objFileReader.result;
var base64 = 'base64,';
var dataStart = fileContents.indexOf(base64) + base64.length;
fileContents = fileContents.substring(dataStart);
self.uploadProcess(component, file, fileContents);
});
objFileReader.readAsDataURL(file);
},
uploadProcess: function(component, file, fileContents) {
var startPosition = 0;
var endPosition = Math.min(fileContents.length, startPosition + this.CHUNK_SIZE);
this.uploadInChunk(component, file, fileContents, startPosition, endPosition, '');
},
uploadInChunk: function(component, file, fileContents, startPosition, endPosition, attachId) {
var getchunk = fileContents.substring(startPosition, endPosition);
var action = component.get("c.AccountWithAttachment");
var accname = component.get("v.AccountName");
console.log("--------" + accname);
action.setParams({
AccountName: accname,
fileName: file.name,
base64Data: encodeURIComponent(getchunk),
contentType: file.type,
fileId: attachId
});
// set call back
action.setCallback(this, function(response) {
// store the response / Attachment Id
attachId = response.getReturnValue();
var state = response.getState();
if (state === "SUCCESS") {
alert("Success");
} 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");
}
}
});
$A.enqueueAction(action);
}
})
Controller: (FileUploadToController)
public with sharing class FileUploadToController {
@AuraEnabled
public static void AccountWithAttachment(String AccountName, String fileName, String base64Data, String contentType, String fileId) {
Account ac = new Account();
ac.Name = AccountName;
insert ac;
if (fileId == '') {
fileId = saveTheFile(ac.Id, fileName, base64Data, contentType);
}
}
public static Id saveTheFile(Id parentId, String fileName, String base64Data, String contentType) {
base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
Attachment oAttachment = new Attachment();
oAttachment.parentId = parentId;
oAttachment.Body = EncodingUtil.base64Decode(base64Data);
oAttachment.Name = fileName;
oAttachment.ContentType = contentType;
insert oAttachment;
return oAttachment.Id;
}
}
Lightning Application: (UploadAttachmentApp)
<aura:application extends="force:slds">
<c:UploadAttachment/>
</aura:application>
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
If I want it to work on my custom object Feedback, then what to do. actually I have on Audio recorder there. I want to attach that recording in that Object's detail page.