Returning files from rails

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

Beginner rails question: How does one return a file from a controller in rails?

I'm familiar with returning/rendering JSON objects. However I've never returned/rendered a file w/ an arbitrary extension.

From reading around SO it sounds like render :nothing => true could help. I'm just looking for some guidance or relevant documentation.

回答1:

You can use the built-in rails send_file or send_data method.

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")

To stream generated data (e.g. for a generated pdf), use send_data:

send_data(your_data,   :filename => "client-suggested-filename",   :type => "mime/type")

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.

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).



转载请标明出处:Returning files from rails
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!