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);
this.saveToSharePoint();
});
this.fileReader.readAsDataURL(this.file);
}
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.setMethod('POST');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setHeader('Accept', 'application/json;odata=verbose');
req.setHeader('content-length',String.valueof(body.length()));
req.setHeader('Authorization', 'Bearer '+accessToken);
req.setEndpoint(endpointUrl);
//req.setBody(body);
req.setBodyAsBlob(Blob.valueOf(body));
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.