admin管理员组

文章数量:1289879

I'm generating gzip files from python using the following code: (using python 3)

    file = gzip.open('output.json.gzip', 'wb')
    dataToWrite = json.dumps(data).encode('utf-8')
    file.write(dataToWrite)
    file.close()

However, I'm trying to read this file now in Javascript using the Pako library (I'm using Angular 2):

this.http.get("output.json.gzip")
      .map((res:Response) => {
        var resText:any = new Uint8Array(res.arrayBuffer());
        var result = "";
        try {
          result = pako.inflate(resText, {"to": "string"});
        } catch (err) {
          console.log("Error " + err);
        }
        return result;

      });

But I'm getting this error in the console: unknown pression method. Should I be doing something else to properly inflate gzip files?

I'm generating gzip files from python using the following code: (using python 3)

    file = gzip.open('output.json.gzip', 'wb')
    dataToWrite = json.dumps(data).encode('utf-8')
    file.write(dataToWrite)
    file.close()

However, I'm trying to read this file now in Javascript using the Pako library (I'm using Angular 2):

this.http.get("output.json.gzip")
      .map((res:Response) => {
        var resText:any = new Uint8Array(res.arrayBuffer());
        var result = "";
        try {
          result = pako.inflate(resText, {"to": "string"});
        } catch (err) {
          console.log("Error " + err);
        }
        return result;

      });

But I'm getting this error in the console: unknown pression method. Should I be doing something else to properly inflate gzip files?

Share Improve this question asked Dec 6, 2017 at 23:15 Ashwin RamaswamiAshwin Ramaswami 91313 silver badges22 bronze badges 2
  • You've encoded it into utf-8. Where do you decode it? – John Mee Commented Dec 6, 2017 at 23:18
  • How do I decode it using JS? – Ashwin Ramaswami Commented Dec 7, 2017 at 3:08
Add a ment  | 

1 Answer 1

Reset to default 11

Turns out that I needed to use the res.blob() function to get the true binary data, not res.arrayBuffer(); and then convert the blob to the array buffer:

return this.http.get("output.json.gzip", new RequestOptions({ responseType: ResponseContentType.Blob }))
      .map((res:Response) => {
        var blob = res.blob();
        var arrayBuffer;
        var fileReader = new FileReader();
        fileReader.onload = function() {
            arrayBuffer = this.result;
            try {
              let result:any = pako.ungzip(new Uint8Array(arrayBuffer), {"to": "string"});
              let obj = JSON.parse(result);
              console.log(obj);
            } catch (err) {
              console.log("Error " + err);
            }
        };
        fileReader.readAsArrayBuffer(blob);
        return "abc";
      });

本文标签: javascriptPako not able to deflate gzip files generated in pythonStack Overflow