How to read a remote file and convert it to a Base64 string [JavaScript]

This code is based on the one found on StackOverflow — it’s compatible with IE8+, and all modern browsers:

    // get the remote file binary content
    function getBinary(file, callback) {
      var convertResponseBodyToText = function(e) { return e };
      var xhr = new XMLHttpRequest();  
      xhr.open("GET", file, true);
      if (xhr.overrideMimeType) xhr.overrideMimeType("text/plain; charset=x-user-defined")
      else {
        // for IE8 the binary file are not read correctly, and the only way is to use VBScript
        // see http://stackoverflow.com/questions/1919972/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie
        xhr.setRequestHeader("Accept-Charset", "x-user-defined");
        var VB_Fix_IE = '<script language="VBScript">'+"\r\n"
                      + "Function IEBinaryToArray_ByteStr(Binary)\r\n"
                      + "  IEBinaryToArray_ByteStr = CStr(Binary)\r\n"
                      + "End Function\r\n"
                      + "Function IEBinaryToArray_ByteStr_Last(Binary)\r\n"
                      + "  Dim lastIndex\r\n"
                      + "  lastIndex = LenB(Binary)\r\n"
                      + "  if lastIndex mod 2 Then\r\n"
                      + "    IEBinaryToArray_ByteStr_Last = Chr( AscB( MidB( Binary, lastIndex, 1 ) ) )\r\n"
                      + "  Else\r\n"
                      + "    IEBinaryToArray_ByteStr_Last = "+'""'+"\r\n"
                      + "  End If\r\n"
                      + "End Function\r\n"
                      + "\<\/script>\r\n";
        document.write(VB_Fix_IE);
        
        convertResponseBodyToText = function(binary) {
          var byteMapping = {};
          for ( var i = 0; i < 256; i++ ) {
            for ( var j = 0; j < 256; j++ ) {
              byteMapping[ String.fromCharCode( i + j * 256 ) ] = String.fromCharCode(i) + String.fromCharCode(j);
            }
          }
          var rawBytes = IEBinaryToArray_ByteStr(binary);
          var lastChr = IEBinaryToArray_ByteStr_Last(binary);
          return rawBytes.replace(/[\s\S]/g, function( match ) { return byteMapping[match]; }) + lastChr;
        };

      }
      xhr.onreadystatechange = function (aEvt) {
        if (xhr.readyState == 4) {
          if(xhr.status == 200) {
            var data = (xhr.overrideMimeType ? xhr.responseText : convertResponseBodyToText(xhr.responseBody));
            callback(data);
          } else {
            console.log("Cannot find the remote file")
          }
        }
      };
      xhr.send(null);
    }

    // convert the file content to a Base64 string
    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;
    }

    getBinary('http://your.site.com/879258.jpeg', function(binary) {
      console.log(base64Encode(binary))
    })

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*