Ajax call to return PDF file as base64 string

﹥>﹥吖頭↗ 提交于 2020-01-30 10:55:07

问题


Im using ajax in an angular js environment to called a local file (a pdf file). The called is successful, however the data return by the ajax call is in garbled code (not sure if i used the right term here, but is just like opening a pdf file using a text editor). Is there anyway that i could get the return result as base64 string?

The reason behind this is to merge up with some of the existing pdf , but before that, i would need the base64 string of the pdf. Below are my ajax call code,

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

回答1:


I managed to convert the pdf file (garbled code) to a base64 string, the proper definition should be converting binary file to base64.

Below is the answer, thanks to @DaTebe and a reference answer from:

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

The answer,

  1. First, write two methods for the conversion from the referenced answer

    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. To use it, just go with:

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



来源:https://stackoverflow.com/questions/37787318/ajax-call-to-return-pdf-file-as-base64-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!