Rendering file with MIME Type in rails

▼魔方 西西 提交于 2019-12-18 11:50:12

问题


Here's the code:

render :file => @somedir + "/blah.xml"

...but the resulting MIME type is text/html when I check in FireBug. How do I specify a MIME type in this case?


回答1:


Actually there are two ways to set the content-type (I think this is what you mean by mime-type). You should use the second option, if it works for your Rails version.

class FileController < ApplicationController

  def index
    filename = 'some.xml'

    extname = File.extname(filename)[1..-1]
    mime_type = Mime::Type.lookup_by_extension(extname)
    content_type = mime_type.to_s unless mime_type.nil?

    # 1
    #headers['Content-Type'] = content_type
    #render :file => filename

    # 2
    render :file => filename, :content_type => content_type
  end

end

Hope this helps!




回答2:


render :file => @somedir + "/blah.xml", :content_type => Mime::XML



回答3:


What about

headers["Content-Type"] = "text/xml"

? Hope that helps.




回答4:


Take a look here. Basically you need to use render :xml => blah.to_xml




回答5:


Per http://api.rubyonrails.org/classes/Mime/Type.html, you could specify it like so:

render file: @somedir + "/blah.xml", mime_type: Mime::Type.lookup("text/xml")  


来源:https://stackoverflow.com/questions/299999/rendering-file-with-mime-type-in-rails

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