J. H.
J. H.

Reputation: 79

Send zip binary data over ActionCable

An ActiveJob generates a zip in a Tempfile, reads its data to a variable, upon completion of the job, broadcasts the data, Base64 encoded, to the client, client downloads data via saveAs

The end result can't be decompressed/is corrupted.

I suspect that something gets lost when encoding/decoding, the zip creation method worked before in a controller but couldn't be used in production because, obviously, it took too long, so I tried this approach, I just can't get it to work.

Relevant part of the Job:

...
zip_data = File.read(temp_file.path)
encoded_zip_data = Base64.encode64(zip_data)
ActionCable.server.broadcast(
    "export_channel_#{uuid}", { zip: encoded_zip_data }
)
...

Relevant part of the coffee that handles the received data:

...
received: (data) ->
  blob = new Blob([ window.atob data.zip ], {
    type: "application/zip"
  })
  saveAs blob, 'data.zip'
...

Upvotes: 0

Views: 633

Answers (1)

J. H.
J. H.

Reputation: 79

This solved it.

str2bytes = (str) ->
  bytes = new Uint8Array(str.length)
  i = 0
  while i < str.length
    bytes[i] = str.charCodeAt(i)
    i++
  bytes

Adding the above plus doing this in my receiving function

received: (data) ->
  blob = new Blob([ str2bytes(window.atob(data.zip)) ], {
    type: "application/zip"
  })

  saveAs blob, 'data.zip'

Upvotes: 2

Related Questions