Returning files from rails

前端 未结 1 916
悲哀的现实
悲哀的现实 2021-01-02 23:52

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 n

相关标签:
1条回答
  • 2021-01-03 00:19

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

    0 讨论(0)
提交回复
热议问题