问题描述
初学者Rails问题:如何从Rails中的控制器返回文件?
Beginner rails question: How does one return a file from a controller in rails?
我熟悉返回/渲染JSON对象.但是,我从未返回/渲染带有任意扩展名的文件.
I'm familiar with returning/rendering JSON objects. However I've never returned/rendered a file w/ an arbitrary extension.
从SO的阅读中看来,render :nothing => true
可能会有所帮助.我只是在寻找一些指导或相关文档.
From reading around SO it sounds like render :nothing => true
could help. I'm just looking for some guidance or relevant documentation.
推荐答案
您可以使用内置导轨 send_file 或 send_data 方法.
You can use the built-in rails send_file or send_data method.
要流式传输文件(例如,用于文件代理端点),请使用send_file:
To stream a file (e.g. for a file proxy endpoint), use send_file:
send_file("#{RAILS_ROOT}/path/to/file/on/server",
:filename => "client-suggested-filename",
:type => "mime/type")
要流式传输生成的数据(例如,生成的pdf),请使用send_data:
To stream generated data (e.g. for a generated pdf), use send_data:
send_data(your_data,
:filename => "client-suggested-filename",
:type => "mime/type")
文件扩展名和mime类型不必匹配,但它们可能仅应符合最终用户的期望.例如,如果发送的哑剧类型为application/pdf
,则应将:filename
设置为something.pdf
.
The file extension and mime type don't have to match up, but they probably should just to conform to end user expectations. For example, if you are sending with a mime type of application/pdf
, you should really set the :filename
to something.pdf
.
如果您不确定要发送的文件的MIME类型,可以检查此Wikipedia页面或使用 mime-types gem. (或者,如果您正在从存储了mime类型的数据库中读取数据,请使用该类型.)
If you're not sure what the mime type is for the file you are sending, you can check this wikipedia page or use the mime-types gem. (Or if you are reading from a database that stores the mime type, use that).
这篇关于从Rails返回文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!