简体   繁体   English

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

[英]Convert PDF file into Base64 string with JavaScript

I have a link to a local pdf file and I need that file as a base64 string. 我有一个本地pdf文件的链接,我需要将该文件作为base64字符串。 I'm programming with JavaScript. 我正在用JavaScript编程。 Does anybody know how I can get this string? 有人知道我怎么能得到这个字符串吗?

UPDATE: 更新:

I have to file object because I downloaded the pdf 我必须提交对象,因为我下载了pdf文件

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

With Screw-FileReader & fetch 使用Screw-FileReader读取

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. 我可以为您提供一些理由,说明您为什么不需要base64字符串以及它为什么不方便。 But i don't know why you need it... The overall reason is URL.createObjectURL and that it's ~3x larger 但我不知道您为什么需要它...总体原因是URL.createObjectURL ,它的大小约大3倍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM