0

I converted a pdf file in base64 with javascript.

function convertToBase64() {
    //Read File
    var selectedFile = document.getElementById("inputFile").files;
            var cvfiles = document.getElementById("cvid");

    //Check File is not Empty
    if (selectedFile.length > 0) {
        // Select the very first file from list
        var fileToLoad = selectedFile[0];
        // FileReader function for read the file.
        var fileReader = new FileReader();
        var base64;
        // Onload of file read the file content
        fileReader.onload = function(fileLoadedEvent) {
            base64 = fileLoadedEvent.target.result;
            // Print data in console
            console.log("result" + base64);

           // console.log(base64);
        };
        // Convert data to base64
        fileReader.readAsDataURL(fileToLoad);



    }
}

An example of the result

 data:application/pdf;base64,JVBERi0xLjUKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3RoIDMgMCBSL0ZpbHRlci9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nD2LuwoCMRBF+/mKWwuJM3lsJhCmELSwWwhYiJ2PTnAbf991V+TCKQ7nshe86QUGew6KXLMPJUOTeB0E041OGzzXYt70oF2nyvOtZPVJK/oV24NAAvr93FgsNQ7mpHHkZC42zgujafuJ4dustpgLjXVhtfi/2qUfad9ppBEfPSwi5wplbmRzdHJlYW0KZW5kb2JqCgozIDAgb2JqCjEzMQplbmRvYmoKCjUgMCBvYmoKPDwvTGVuZ3RoIDYgMCBSL0ZpbHRlci9GbGF0ZURlY29kZS9MZW5ndGgxIDI5NzY+PgpzdHJlYW0KeJzlVUtsG1UUvW/G8cT5OI4T2/k0zmRiTz5NJonjT5KGpCFtU7fpJ2mwCv3QkePYbhzbjCdNSypaaISQaAUIIXVRsYLSBUJISLBAQqqK+CyKSlkgQSpASFVBXfGp2i5s7oyfQxIq2gU7ZjTvnXvfffeee99nVGU+AiY4DSxYwnNyWigvLQaACwDEGk2cmFnsIkHE7wOwNbGIPP1rxUIngOELtPHHUNGZ+4gFKEIRXLE59fgR9ucylF0otyZSYfkIG2JQHkfZPicfT7fCboRF09jwSXkucm5qsg3lJfzup1MZtR8+ywGUntbG8SP4ag/6JEZNZlhDkZErNsH/9SHgz91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ODY4QUM+CjxEREUwNThGRkY1MTM5MThFRTdCQjREMDQxNTk4NjhBQz4gXQovRG9jQ2hlY2tzdW0gLzI4RkZDM0Q0REVENDU0Q0MzRjI1MUM3ODM3NkRDNDI3Cj4+CnN0YXJ0eHJlZgozMzkxCiUlRU9GCg==

Then I sent the result to create a ContentVersion

fileName = 'KKK.pdf' ;
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S'; // S = within Salesforce, E = External
System.debug('file 64 ' + fileBody ) ;
cv.VersionData = EncodingUtil.base64Decode(fileBody) ;
cv.Title = fileName;
cv.PathOnClient = filename;
insert cv;

I tried with a pdf document, almost blank with a single word. to see if the problem was that the pdf is too big but I still have the same error message "unrecognized base64"

if I put

   Blob.valueOf(fileBody) 

instead of

   EncodingUtil.base64Decode(fileBody)

the Apex class does not send me an error. but the document file is wrong

0

You need to remove the pre-amble from your base64 string in Javascript i.e.

const base64Mark = 'base64,';
const dataStart = base64.indexOf(base64Mark) + base64Mark.length;

base64 = base64.substring(dataStart);

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.