Search code examples
javascripthtmljszip

JavaScript dynamically set img src to HTML5 uploaded file


I am using the JSZip library to extract uploaded epub files. I can successfully iterate through it and display the name of the file within the library with:

zipEntry.name;

And I can find the cover.jpg file with string comparisons. How can I set the source of a image on my html page to that cover? I have tried:

src=zipEntry;

and

src=zipEntry.name;

Is it even possible? Is there a easy way to do it with jQuery?


Solution

  • I tried putting an empty image on a page

    <img id="testimg" />
    

    and then using this javascript code to show a PNG image from a zip file:

    var zipEntry = zip.file('test.png');
    $('#testimg')[0].src = 'data:image/png;base64,' + base64_encode(zipEntry.asBinary());
    

    This worked for me. See this JSFiddle for a demo of the working code.

    You will need the function base64_encode() (from phpjs.org):

    function base64_encode (data) {
      // phpjs.org
      var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
      var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        enc = "",
        tmp_arr = [];
    
      if (!data) {
        return data;
      }
    
      do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);
    
        bits = o1 << 16 | o2 << 8 | o3;
    
        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;
        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;
    
        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
      } while (i < data.length);
    
      enc = tmp_arr.join('');
    
      var r = data.length % 3;
    
      return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
    }