1

Currently, I am able to pass a single file from the lightning component to the apex controller. But please let me know how to pass multiple files to the apex controller.

Here I need to pass multiple files (listFile) to the apex controller.

public with sharing class FileUploadController {

    @AuraEnabled
    public static Id SaveFile(Id parentId, String fileName, String base64Data, String contentType) {
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
        Attachment attach = new Attachment();
        attach.parentId = parentId;
        attach.Body = EncodingUtil.base64Decode(base64Data);
        attach.Name = fileName;
        attach.ContentType = contentType;
        Insert attach;
        return attach.Id;
    }
}

JavaScript controller:

sampleFunction: function(component, event, helper) {
    var index = event.target.dataset.index;
   var listFile = component.get("v.listFile");
    listFile.splice(index, 1);
    component.set("v.listFile", listFile);
}

1 Answer 1

0

You can start with some classes:

public class File {
  @AuraEnabled public String name;
  @AuraEnabled public String content;
  @AuraEnabled public String contentType;
}

public class Request {
  @AuraEnabled public Id parentId;
  @AuraEnabled public File[] files;
}

Then use that as the parameter:

@AuraEnabled public static Id[] SaveFile(Request req) { 
  Attachment[] files = new Attachment[];
  for(File file: req.files) {
    Attachment attach = new Attachment();
    attach.parentId = req.parentId;
    attach.Name = file.Name;
    attach.Body = EncodingUtil.base64decode(file.content);
    attach.ContentType = file.contentType;
    files.add(attach);
  }
  insert files;
  return new List<Id>(
    new Map<Id, Attachment>(
      files
    ).keySet()
 );
}

You'll want to adjust your JavaScript accordingly. base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8'); Attachment attach = new Attachm

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .