Jszip: How do I get a svg or image of zip through JS

Created on 26 Jun 2017  Â·  1Comment  Â·  Source: Stuk/jszip

For example, I have a compressed file, there are pictures, JS, HTML, etc., I would like to get through the JSZIp ,but I can get a right base64 of a image and I don't know how to show a svg from a compressed file. Thanks for your help !

and the result is data:image/png;base64,fVhnOBuOt1aCxI49ggiVqKpdktaIPSJmz......
the right should be : data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA......

JSZipUtils.getBinaryContent("svg/svg.zip", function(err, data) {
  if(err) {
    throw err; // or handle err
  }
  JSZip.loadAsync(data).then(function(unzipInfo) {
    var imageSrc = {};
    if(unzipInfo.files){
      var strRegex = "(.jpg|.png|.gif|.ps|.jpeg)$";
      var re=new RegExp(strRegex);
      for(var i in unzipInfo.files){
        var fileName = unzipInfo.files[i];
        if (re.test(i.toLowerCase())){
          var buffer = fileName._data.compressedContent,
            str = _arrayBufferToBase64(buffer),
            pIndex = i.indexOf("."),
            type = i.substr(pIndex + 1),
            res = 'data:image/' + type + ';base64,';
          imageSrc[i] = res + str;
          if(i == "11.png"){
            console.log("imageSrc"+i+":"+imageSrc[i]);
          }
        }
      }
    }
  });       
});

function _arrayBufferToBase64(buffer) {
  var binary = '';
  var bytes = new Uint8Array(buffer);
  var len = bytes.byteLength;
  for(var i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}
questiosupport

Most helpful comment

fileName._data.compressedContent

_data is an internal object, you shouldn't use it. Use async: .async({type: "base64"}) (warning, this returns a promise).

You can also use a blob url instead:

fileName.async("blob").then(function (blob) {
  var blobUrl = URL.createObjectURL(blob);
});

It should work the same way as a base64 data url.

Does this solve your issue ?

>All comments

fileName._data.compressedContent

_data is an internal object, you shouldn't use it. Use async: .async({type: "base64"}) (warning, this returns a promise).

You can also use a blob url instead:

fileName.async("blob").then(function (blob) {
  var blobUrl = URL.createObjectURL(blob);
});

It should work the same way as a base64 data url.

Does this solve your issue ?

Was this page helpful?
0 / 5 - 0 ratings