Search code examples
ruby-on-railsrubyruby-on-rails-3ziprubyzip

ruby on rails the archive is in unknown format or damaged error upon send_data


I have the following code to zip some files and download it to the users desktop:

def download
    info.find(params[:id])

  if File.exists?("my_file.zip")
    File.delete("my_file.zip")
  end

  zipfile = Zip::ZipFile.open("my_file.zip", Zip::ZipFile::CREATE)
  file1 =  "#{Rails.root}/tmp/myfile1.txt"
  file2 =  "#{Rails.root}/tmp/myfile2.txt"

  File.open(file1, 'wb') { |file| file.write(info.first['my_file1']) }
  File.open(file2, 'wb') { |file| file.write(info.first['my_file2']) }

  zipfile.add("myfile1.txt", file1)
  zipfile.add("myfile2.txt", file2)

  zipfile.close

  File.delete(file1)
  File.delete(file2)

  send_data zipfile, :type => 'application/zip', :filename => "test.zip"
end

The code seems to zip the files and downloads it to the user's computer. But it throws the following error when I try to open it:

the archive is in unknown format or damaged

I don't think the file is corrupted, because when I sftp to the server and open the zip file with the same software, it works fine and shows me all the files.

Could it be the following line that is incorrect?

send_data zipfile, :type => 'application/zip', :filename => "test.zip"

Solution

  • It looks like you're sending the zipfile object, the send_data method sends the binary data contained in the given object. So it's likely just sending the data zipfile.to_s.

    send_file is probably what you want, like this:

    send_file 'my_file.zip', type: 'application/zip', filename: 'test.zip'