on file upload below function is called in LWC.

LWC Function

uploadHelper() {
    this.file = this.filesUploaded[0]; 
    this.fileReader = new FileReader();
    this.fileReader.onloadend = (() => {
        this.fileContents = this.fileReader.result;
        let base64 = 'base64,';
        this.content = this.fileContents.indexOf(base64) + base64.length;
        this.fileContents = this.fileContents.substring(this.content);


passed to apex method

saveToExternalSystem() {
    sendFile({idParent: this.recordId, strFileName: this.file.name, base64Data: btoa(this.fileContents) })
        .then(result => {
            window.console.log('result ====> ' + result);
            this.showLoadingSpinner = false;
            this.fileName = this.fileName + ' - Uploaded Successfully';
            this.UploadFile = 'File Uploaded Successfully';


Apex Method -

public static Map < String,Object > postFile (Id idParent,String accessToken, 
String strFileName, String base64Data) {
       String file = '\''+strFileName+'\'';
       blob blfile = EncodingUtil.base64Decode(base64Data);
       String body = blfile.toString();
       Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.setHeader('Accept', 'application/json;odata=verbose');
        req.setHeader('Authorization', 'Bearer '+accessToken);
        System.debug('req:--> ' + req);
        HttpResponse res = h.send(req);

After this file is successfully getting uploaded, but when i try to open the file it says "file cannot be opened. Try to reload". basically content is getting corrupted.

How to resolve this.


Uploading the file through file-reader in JS can be used for a file-size of maximum 716kb. Moreover, you may run in issues like this. I would suggest a different flow:

  1. Use standard fileUpload with recordId as userId.

  2. After the file(s) are uploaded, when user clicks Done, you get the event onuploadfinished which will have information about uploaded content documents.

  3. In that method, invoke a callout to POST it to external system and appropriate user message can be shown while its processing callout.

  4. After callout finishes, delete the document (probably using async apex).

The main advantage of this flow is you can have 2GB limit on file upload and its standard component (have to check limit on callout size)

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.