Ruby-on-rails 在 rails 中使用 MIME 类型渲染文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/299999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:47:23  来源:igfitidea点击:

Rendering file with MIME Type in rails

ruby-on-railsrubyrendermime-types

提问by user38684

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?

...但是当我签入 FireBug 时,生成的 MIME 类型是 text/html。在这种情况下如何指定 MIME 类型?

回答by blindgaenger

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.

实际上有两种设置内容类型的方法(我认为这就是你所说的 mime-type)。您应该使用第二个选项,如果它适用于您的 Rails 版本。

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!

希望这可以帮助!

回答by gerrit

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

回答by Honza

What about

关于什么

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

? Hope that helps.

? 希望有帮助。

回答by srboisvert

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

看看这里。基本上你需要使用 render :xml => blah.to_xml

回答by konyak

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

根据http://api.rubyonrails.org/classes/Mime/Type.html,您可以像这样指定它:

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