17

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?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user38684
  • 171
  • 1
  • 1
  • 3

5 Answers5

35

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!

blindgaenger
  • 2,030
  • 2
  • 16
  • 10
  • Alternative way of getting mime type from a file name/path `MIME::Types.type_for("some.xml").first.content_type` – Amit Patel Mar 21 '16 at 10:05
16
render :file => @somedir + "/blah.xml", :content_type => Mime::XML
gerrit
  • 1,539
  • 14
  • 13
3

What about

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

? Hope that helps.

Honza
  • 4,349
  • 2
  • 24
  • 40
2

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

srboisvert
  • 12,679
  • 15
  • 63
  • 87
  • Thanks, but the request has no extension, and I think responds_to uses the extension to determine the format. Am I wrong? – user38684 Nov 18 '08 at 21:01
0

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")  
konyak
  • 10,818
  • 4
  • 59
  • 65