简体   繁体   English

如何在Java脚本中将PDF文件转换为base64字符串

[英]How to convert a PDF file into a base64 string in java script

I have created an app in sencha touch cordova, and in my app I have a functionality to download PDFs. 我已经在sencha touch cordova中创建了一个应用程序,并且在我的应用程序中,我具有下载PDF的功能。

I have successfully downloaded a pdf file, but now I want to convert the PDF into a base64 string using JavaScript. 我已经成功下载了pdf文件,但是现在我想使用JavaScript将PDF转换为base64字符串。

Can anybody tell me how to do it? 有人可以告诉我该怎么做吗?

See if your JavaScript environment has the " atob " and " btoa " functions available: 查看您的JavaScript环境是否具有“ atob ”和“ btoa ”功能:

var encodedData = window.btoa("Hello, world"); // encode a string
var decodedData = window.atob(encodedData); // decode the string

These convert a string to and from Base64 encoding. 这些将字符串与Base64编码相互转换。

Trying using the logic below. 尝试使用以下逻辑。

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

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);
    }
}

Note : This snippet was taken from stackoverflow, but I dont remember the link :( 注意:此摘录摘自stackoverflow,但我不记得链接了:(

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

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