Will
Will

Reputation: 4693

How to set Content Type for a temporary file

I have a rake task that fetches XML documents and saves them to a model in my app. The task worked until I added validation of content_type to the model

The task now gives the error:

Datafile content type is invalid, Datafile is invalid

How can i set the tmp file's content_type to text/xml so that the validation passes?

The task code is below:

  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

Upvotes: 6

Views: 6708

Answers (1)

Will
Will

Reputation: 4693

I was able to find out the content-type to use like this:

gem install mime-types

and added to my rake task:

require 'mime/types' 

I then broke into the pry repl and used

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

which enabled me to add the correct mime type to the model validation:

application/xml

I'm not sure why the files are application/xml when the form uploaded files are text/xml but in hindsight, a pretty obvious fix!

Upvotes: 3

Related Questions