【问题标题】:How to set Content Type for a temporary file如何为临时文件设置内容类型
【发布时间】:2014-02-16 07:23:50
【问题描述】:

我有一个 rake 任务,它获取 XML 文档并将它们保存到我的应用程序中的模型中。该任务一直有效,直到我将 content_type 验证添加到模型中

任务现在给出错误:

Datafile content type is invalid, Datafile is invalid

如何将 tmp 文件的 content_type 设置为 text/xml 以便验证通过?

任务代码如下:

  task :fetch_documents => :environment do        
    Net::FTP.open("www.example.com", "xxxxx", "xxxxx") do |ftp|          
      ftp.nlst.each do |file_name|
        tmp = Tempfile.new(['foo', '.xml' ])
        ftp.gettextfile(file_name, tmp.path)
        # save it
        document = Document.new
        document.file_name = File.basename(file_name)
        document.datafile = tmp
        document.save!
        tmp.close
        end
     end
  end

【问题讨论】:

  • 这可能会有所帮助 - stackoverflow.com/questions/11621863/…
  • @devanand 谢谢,但不只是 s3,我只是在本地运行任务。
  • @devanand 实际上,这确实有帮助:) - 它导致使用 M​​IME::Types.type_for("filename.xml").first.content_type 来获取内容类型,即 application/xml - 将其添加到模型验证中让我通过了。谢谢!

标签: ruby-on-rails paperclip


【解决方案1】:

我能够像这样找出要使用的内容类型:

gem install mime-types

并添加到我的 rake 任务中:

require 'mime/types' 

然后我闯入了 pry repl 并使用了

MIME::Types.type_for(tmp.path).first.content_type 

这使我能够将正确的 mime 类型添加到模型验证中:

application/xml

当表单上传的文件是 text/xml 时,我不确定为什么文件是 application/xml,但事后看来,这是一个非常明显的解决方法!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-19
    • 2013-01-30
    • 2016-09-28
    • 2021-04-20
    • 2012-10-19
    • 2010-11-22
    • 2012-02-28
    相关资源
    最近更新 更多