Rails http对Donwload excel文件的响应 [英] rails http response to Donwload excel file
问题描述
我在github中看到了这段代码
i saw this code in github
require "csv"
csv_str = CSV.generate do |csv|
csv << ["awesome", "csv"]
end
result = IO.popen("secure-spreadsheet --password secret", "r+") do |io|
io.write(csv_str)
io.close_write
io.read
end
File.open("output.xlsx", "w") { |f| f.write(result) }
此代码将Excel文件(output.xlsx)存储在我的项目文件中.
this code store a Excel file(output.xlsx) in my project file.
我如何转换此存储文件方案"?进入在浏览器中下载文件"?
how can i convert this "store file scenario" in to "download the file in the browser"?
推荐答案
在您的config/initializers/mime_types.rb中注册xlsx mime_type(默认情况下在Rails中不可用):
In your config/initializers/mime_types.rb register the xlsx mime_type(It is not available in Rails by default) :
Mime::Type.register "application/xlsx", :xlsx
假设您执行excel生成的代码有效并且位于名为 excel_file
的控制器方法(私有)中(我认为将其提取到service/lib类更好):
Assuming your code that does the excel generation works and is in a controller method(private) named excel_file
(I think its better to extract to a service/lib class):
def excel_file
csv_str = CSV.generate do |csv|
csv << ["awesome", "csv"]
end
IO.popen("secure-spreadsheet --password secret", "r+") do |io|
io.write(csv_str)
io.close_write
io.read
end
end
在控制器操作中,您应该可以执行以下操作
In your controller action you should be able to do something like this
def download_excel
respond_to do |format|
format.xlsx { send_data excel_file, type: 'application/xlsx; header=present', disposition: "attachment", filename: "output.xlsx" }
end
end
( ActionController#send_data 将给定的二进制数据发送到浏览器".通过该链接了解详情)
( ActionController#send_data "sends the given binary data to the browser". Read more via that link)
如果有视图,可以有一个下载链接
If you have a view, you can have a download link
<%= link_to "Download", your_download_path(format: "xlsx") %>
用户应该能够通过链接下载excel文件
Users should be able to download the excel file via the link
这篇关于Rails http对Donwload excel文件的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!