0

I have a link to a local pdf file and I need that file as a base64 string. I'm programming with JavaScript. Does anybody know how I can get this string?

UPDATE:

I have to file object because I downloaded the pdf

2

2 Answers 2

3

Try this :-

<input id="inputFile" type="file" onchange="convertToBase64();" />

<script type="text/javascript">
    function convertToBase64() {
        //Read File
        var selectedFile = document.getElementById("inputFile").files;
        //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(base64);
            };
            // Convert data to base64
            fileReader.readAsDataURL(fileToLoad);
        }
    }
</script>

From this

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! I'm not sure where I should put my link. What does document.getElementById("inputFile").files;? Does it return an array of "Files"?
I think it isn't possible to get a file object from an url. Or am I wrong?
2

With Screw-FileReader & fetch

fetch('/file.pdf')
.then(res => res.blob())
.then(blob => blob.dataUrl())
.then(base64 => console.log(base64))

I could give you a few reason why you don't need the base64 string and why it's inconvenient. But i don't know why you need it... The overall reason is URL.createObjectURL and that it's ~3x larger

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.