Rails:ZIP文件显示在浏览器中而不是下载

时间:2011-09-15 06:58:24

标签: ruby-on-rails-3

我的控制器发送一个ZIP文件:

def index
  respond_to do |format|
    format.html  { render :text => open("tmp/test1.zip", "rb").read }
  end
end

问题: ZIP是以浏览器中显示的文字形式接收的 我希望它能够下载。

注意:我写了format.html,因为当我写format.zip时,我得到uninitialized constant Mime::ZIP。这可能是问题的一部分。

4 个答案:

答案 0 :(得分:9)

您可以注册自己的mime类型:

Mime::Type.register "application/zip", :zip

def index
  respond_to do |format|
    format.html  { ... } #do whatever you need for html
    format.csv  { ... } #do whatever you need for csv
    format.zip  { send_file 'your_file.zip' }
  end
end

看看这里:

http://weblog.rubyonrails.org/2006/12/19/using-custom-mime-types

答案 1 :(得分:4)

答案 2 :(得分:2)

您可以跳过respond_to内容并手动设置内容类型:

def index
  render :file => '/full/path/to/tmp/test1.zip', :content_type => 'application/zip', :status => :ok
end

有关详细信息,请参阅Layouts and Rendering in Rails指南。

如果您也想支持.csv,那么您可以尝试查看params[:format]

def index
  if params[:format] == 'zip'
    # send back the zip as above.
  elsif params[:format] == 'csv'
    # send back the CSV
  else
    # ...
  end
end

看看send_file正如Marian Theisen所暗示的那样。

答案 3 :(得分:0)

def index
  send_data File.read('/full/path/to/tmp/test1.zip'), filename: "test1.zip"
end
相关问题