Search code examples
meteoriron-routerjszip

Meteor + Iron Router + JSZip not working


I'm trying to create and serve a zip file using Meteor. Here's what I have:

Router.map ->
  @route "data",
    where: 'server'
    path: "/data"
    action: ->
      this.response.writeHead 200,
        'Content-Type': 'application/zip'
        'Content-Disposition': "attachment; filename=data.zip"
      zip = new JSZip()
      zip.file "Hello.txt", "Hello World"
      this.response.end zip.generate({ 'type': 'string', 'compression': 'DEFLATE'})

I have jszip.min.js and jszip-deflate.js. A zip file is created and I can download it, but I can't open the file with the archive manager (corrupted). If I open data.zip with a text editor I see "PK" plus two hex characters.

How can I create a zip file and return it?

ANSWER:

Use the default base64 encoding for zipping and specify the response encoding in the end/write method:

Router.map ->
  @route "data",
    where: 'server'
    path: "/data"
    action: ->
      this.response.writeHead 200,
        'Content-Type': 'application/zip'
        'Content-Disposition': "attachment; filename=data.zip"

      zip = new JSZip()
      zip.file "Hello.txt", "Hello World"
      file = zip.generate({ 'compression': 'DEFLATE' })

      this.response.end file, 'base64'

Solution

  • Use the default base64 encoding for zipping and specify the response encoding in the end/write method:

    Router.map ->
      @route "data",
        where: 'server'
        path: "/data"
        action: ->
          this.response.writeHead 200,
            'Content-Type': 'application/zip'
            'Content-Disposition': "attachment; filename=data.zip"
    
          zip = new JSZip()
          zip.file "Hello.txt", "Hello World"
          file = zip.generate({ 'compression': 'DEFLATE' })
    
          this.response.end file, 'base64'