【问题标题】:How to convert a PDF file into a base64 string in java script如何在javascript中将PDF文件转换为base64字符串
【发布时间】:2015-05-25 04:13:24
【问题描述】:

我在 sencha touch cordova 中创建了一个应用程序,在我的应用程序中我有一个下载 PDF 的功能。

我已成功下载 pdf 文件,但现在我想使用 JavaScript 将 PDF 转换为 base64 字符串。

谁能告诉我怎么做?

【问题讨论】:

    标签: javascript cordova pdf extjs sencha-touch


    【解决方案1】:

    查看您的 JavaScript 环境是否有可用的“atob”和“btoa”函数:

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

    这些将字符串转换为 Base64 编码和从 Base64 编码转换。

    【讨论】:

    • 感谢@David,但它只转换字符串。我需要转换 pdf 文件。
    【解决方案2】:

    尝试使用下面的逻辑。

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

    注意:这个sn-p取自stackoverflow,但我不记得链接:(

    【讨论】:

      猜你喜欢
      • 2017-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 2021-12-13
      • 2012-11-12
      相关资源
      最近更新 更多