{"id":1415,"date":"2014-09-19T17:56:39","date_gmt":"2014-09-19T15:56:39","guid":{"rendered":"http:\/\/blog.kodono.info\/wordpress\/?p=1415"},"modified":"2014-10-29T10:30:16","modified_gmt":"2014-10-29T09:30:16","slug":"how-to-read-a-remote-file-and-convert-it-to-a-base64-string-javascript","status":"publish","type":"post","link":"https:\/\/blog.kodono.info\/wordpress\/2014\/09\/19\/how-to-read-a-remote-file-and-convert-it-to-a-base64-string-javascript\/","title":{"rendered":"How to read a remote file and convert it to a Base64 string [JavaScript]"},"content":{"rendered":"<p>This code is based on the one found on <a href=\"http:\/\/stackoverflow.com\/questions\/7370943\/retrieving-binary-file-content-using-javascript-base64-encode-it-and-reverse-de\">StackOverflow<\/a> &#8212; it&#8217;s compatible with IE8+, and all modern browsers:<\/p>\n<pre class=\"brush:javascript\">\r\n    \/\/ get the remote file binary content\r\n    function getBinary(file, callback) {\r\n      var convertResponseBodyToText = function(e) { return e };\r\n      var xhr = new XMLHttpRequest();  \r\n      xhr.open(\"GET\", file, true);\r\n      if (xhr.overrideMimeType) xhr.overrideMimeType(\"text\/plain; charset=x-user-defined\")\r\n      else {\r\n        \/\/ for IE8 the binary file are not read correctly, and the only way is to use VBScript\r\n        \/\/ see http:\/\/stackoverflow.com\/questions\/1919972\/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie\r\n        xhr.setRequestHeader(\"Accept-Charset\", \"x-user-defined\");\r\n        var VB_Fix_IE = '&lt;script language=\"VBScript\">'+\"\\r\\n\"\r\n                      + \"Function IEBinaryToArray_ByteStr(Binary)\\r\\n\"\r\n                      + \"  IEBinaryToArray_ByteStr = CStr(Binary)\\r\\n\"\r\n                      + \"End Function\\r\\n\"\r\n                      + \"Function IEBinaryToArray_ByteStr_Last(Binary)\\r\\n\"\r\n                      + \"  Dim lastIndex\\r\\n\"\r\n                      + \"  lastIndex = LenB(Binary)\\r\\n\"\r\n                      + \"  if lastIndex mod 2 Then\\r\\n\"\r\n                      + \"    IEBinaryToArray_ByteStr_Last = Chr( AscB( MidB( Binary, lastIndex, 1 ) ) )\\r\\n\"\r\n                      + \"  Else\\r\\n\"\r\n                      + \"    IEBinaryToArray_ByteStr_Last = \"+'\"\"'+\"\\r\\n\"\r\n                      + \"  End If\\r\\n\"\r\n                      + \"End Function\\r\\n\"\r\n                      + \"\\&lt;\\\/script>\\r\\n\";\r\n        document.write(VB_Fix_IE);\r\n        \r\n        convertResponseBodyToText = function(binary) {\r\n          var byteMapping = {};\r\n          for ( var i = 0; i < 256; i++ ) {\r\n            for ( var j = 0; j < 256; j++ ) {\r\n              byteMapping[ String.fromCharCode( i + j * 256 ) ] = String.fromCharCode(i) + String.fromCharCode(j);\r\n            }\r\n          }\r\n          var rawBytes = IEBinaryToArray_ByteStr(binary);\r\n          var lastChr = IEBinaryToArray_ByteStr_Last(binary);\r\n          return rawBytes.replace(\/[\\s\\S]\/g, function( match ) { return byteMapping[match]; }) + lastChr;\r\n        };\r\n\r\n      }\r\n      xhr.onreadystatechange = function (aEvt) {\r\n        if (xhr.readyState == 4) {\r\n          if(xhr.status == 200) {\r\n            var data = (xhr.overrideMimeType ? xhr.responseText : convertResponseBodyToText(xhr.responseBody));\r\n            callback(data);\r\n          } else {\r\n            console.log(\"Cannot find the remote file\")\r\n          }\r\n        }\r\n      };\r\n      xhr.send(null);\r\n    }\r\n\r\n    \/\/ convert the file content to a Base64 string\r\n    function base64Encode(str) {\r\n      var CHARS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\r\n      var out = \"\", i = 0, len = str.length, c1, c2, c3;\r\n      while (i &lt; len) {\r\n        c1 = str.charCodeAt(i++) &#038; 0xff;\r\n        if (i == len) {\r\n          out += CHARS.charAt(c1 >> 2);\r\n          out += CHARS.charAt((c1 &#038; 0x3) &lt;&lt; 4);\r\n          out += \"==\";\r\n          break;\r\n        }\r\n        c2 = str.charCodeAt(i++);\r\n        if (i == len) {\r\n          out += CHARS.charAt(c1 >> 2);\r\n          out += CHARS.charAt(((c1 &#038; 0x3)&lt;&lt; 4) | ((c2 &#038; 0xF0) >> 4));\r\n          out += CHARS.charAt((c2 &#038; 0xF) &lt;&lt; 2);\r\n          out += \"=\";\r\n          break;\r\n        }\r\n        c3 = str.charCodeAt(i++);\r\n        out += CHARS.charAt(c1 >> 2);\r\n        out += CHARS.charAt(((c1 &#038; 0x3) &lt;&lt; 4) | ((c2 &#038; 0xF0) >> 4));\r\n        out += CHARS.charAt(((c2 &#038; 0xF) &lt;&lt; 2) | ((c3 &#038; 0xC0) >> 6));\r\n        out += CHARS.charAt(c3 &#038; 0x3F);\r\n      }\r\n      return out;\r\n    }\r\n\r\n    getBinary('http:\/\/your.site.com\/879258.jpeg', function(binary) {\r\n      console.log(base64Encode(binary))\r\n    })\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>This code is based on the one found on StackOverflow &#8212; it&#8217;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(&#8220;GET&#8221;, file, true); if (xhr.overrideMimeType) xhr.overrideMimeType(&#8220;text\/plain; charset=x-user-defined&#8221;) else { \/\/ for IE8 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_coblocks_attr":"","_coblocks_dimensions":"","_coblocks_responsive_height":"","_coblocks_accordion_ie_support":"","hide_page_title":"","footnotes":""},"categories":[13,33],"tags":[24,152,158],"class_list":["post-1415","post","type-post","status-publish","format-standard","hentry","category-niveau-intermediaire","category-programmation","tag-javascript","tag-niveau-intermediaire","tag-programmation"],"_links":{"self":[{"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/posts\/1415","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/comments?post=1415"}],"version-history":[{"count":7,"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/posts\/1415\/revisions"}],"predecessor-version":[{"id":1425,"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/posts\/1415\/revisions\/1425"}],"wp:attachment":[{"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/media?parent=1415"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/categories?post=1415"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.kodono.info\/wordpress\/wp-json\/wp\/v2\/tags?post=1415"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}