【问题标题】:Ajax call to return PDF file as base64 stringAjax 调用以将 PDF 文件作为 base64 字符串返回
【发布时间】:2016-10-13 17:28:50
【问题描述】:

我在 Angular js 环境中使用 ajax 来调用本地文件(pdf 文件)。调用成功,但是 ajax 调用返回的数据是乱码(不确定我是否在这里使用了正确的术语,但就像使用文本编辑器打开 pdf 文件一样)。无论如何我可以得到base64字符串的返回结果吗?

这背后的原因是与一些现有的 pdf 合并,但在此之前,我需要 pdf 的 base64 字符串。下面是我的ajax调用代码,

$.ajax({           
    url : 'path/to/pdfFile.pdf',
    success : function(data) {
       console.log(data); //expecting base64 string here
    },
    error: function(xhr, textStatus, errorThrown){
      console.log('request failed');
    },
    async : false
});

【问题讨论】:

  • 也许这对你有帮助:stackoverflow.com/questions/7370943/…在接受的答案中有一个函数可以用base64编码响应
  • 嗨@DaTebe,我尝试将返回的数据从ajax传递给你提到的堆栈溢出答案的“base64ArrayBuffer”方法,它给出了一个“无效的数组长度参数”,我需要做的任何事情在将数据传递给方法之前?
  • 嗨@DaTebe,感谢您的指导,我设法将其转换为base64,我现在将发布答案。
  • 很高兴听到!你从 jQuery 切换到 Vanilla JS。但它也应该适用于 jQuery?
  • jQuery?Vanilla Js?我只是在使用 angular js 和普通的 javascript 哈哈

标签: javascript angularjs ajax pdf encoding


【解决方案1】:

我设法将pdf文件(乱码)转换为base64字符串,正确的定义应该是将二进制文件转换为base64。

以下是答案,感谢@DaTebe 和参考答案:

Retrieving binary file content using Javascript, base64 encode it and reverse-decode it using Python

答案,

  1. 首先,编写两个方法用于从引用的答案进行转换

    function base64Encode(str) {
        var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var out = "", i = 0, len = str.length, c1, c2, c3;
        while (i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if (i == len) {
                out += CHARS.charAt(c1 >> 2);
                out += CHARS.charAt((c1 & 0x3) << 4);
                out += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if (i == len) {
                out += CHARS.charAt(c1 >> 2);
                out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
                out += CHARS.charAt((c2 & 0xF) << 2);
                out += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
            out += CHARS.charAt(c3 & 0x3F);
        }
        return out;
    }
    
    function getBinary(file){
        var xhr = new XMLHttpRequest();
        xhr.open("GET", file, false);
        xhr.overrideMimeType("text/plain; charset=x-user-defined");
        xhr.send(null);
        return xhr.responseText;
    }
    
  2. 要使用它,只需:

    var b = getBinary('path/to/pdfFile.pdf');
    var b64 = base64Encode(b);
    控制台.log(b64);

【讨论】:

  • 非常感谢,效果很好!
猜你喜欢
  • 1970-01-01
  • 2017-01-29
  • 2016-05-21
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 2015-04-18
相关资源
最近更新 更多