1

我有以下代码来压缩一些文件并将其下载到用户桌面:

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 archive is in unknown format or damaged

我不认为该文件已损坏,因为当我 sftp 到服务器并使用相同的软件打开 zip 文件时,它可以正常工作并显示所有文件。

可能是以下行不正确吗?

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

1 回答 1

1

看起来您正在发送zipfile对象,该send_data方法发送给定对象中包含的二进制数据。所以它很可能只是发送数据zipfile.to_s

send_file可能是你想要的,像这样:

send_file 'my_file.zip', type: 'application/zip', filename: 'test.zip'
于 2014-11-12T18:48:45.723 回答