最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert PDF file into Base64 string with JavaScript - Stack Overflow

programmeradmin0浏览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

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

Share Improve this question edited Sep 21, 2016 at 13:05 chocolate cake asked Sep 21, 2016 at 12:15 chocolate cakechocolate cake 2,4997 gold badges29 silver badges58 bronze badges 2
  • 4 Possible duplicate of Convert PDF to a Base64-encoded string in Javascript – David R Commented Sep 21, 2016 at 12:17
  • You shouldn't have to base64 the pdf... why do you need that? – Endless Commented Sep 22, 2016 at 20:54
Add a ment  | 

2 Answers 2

Reset to default 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

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

发布评论

评论列表(0)

  1. 暂无评论