使用JavaScript将PDF文件转换为Base64字符串

时间:2016-09-21 12:15:32

标签: javascript pdf base64

我有一个本地pdf文件的链接,我需要该文件作为base64字符串。我是用JavaScript编程的。 有谁知道我怎么能得到这个字符串?

更新

我必须归档对象,因为我下载了pdf

2 个答案:

答案 0 :(得分:3)

试试这个: -

<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>

来自this

答案 1 :(得分:2)

Screw-FileReader&amp; fetch

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

我可以告诉你为什么你不需要base64字符串以及为什么它不方便。但我不知道你为什么需要它...总体原因是URL.createObjectURL并且它大约3倍

相关问题