简体   繁体   中英

Ajax call to return PDF file as base64 string

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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