0

I know this has already been asked before but I couldn't find anything quite like the issue I am facing.

I am using the open() method to download and save the file.

img = Image.new
img.image = open(url)
img.save

This throws an error: Paperclip error while determining content type I found this on SO, but I am on a linux machine so it does not apply:

paperclip Error while determining content type: Cocaine::CommandNotFoundError in Rails 3.2.1

The other way to do this is to use URI.parse(). However I faced issues with it earlier, it seems to be working fine now.

Overall the behaviour from either one open() or URI.parse() has been unpredictable. Sometimes they work sometimes they don't. What is the best one to use in this case and what fail safe strategy can I use?

1
  • do you have require 'open-uri' at the top of your file? Commented Mar 26, 2014 at 8:23

1 Answer 1

2

I have experienced similar problems with certain file types. I'm using Ubuntu 12.04 and file --mime doesn't always manage to find the file type, for example with .doc files.

I got around this by modifing Paperclip to use file --mime where it could, and then fall back to mimetype otherwise.

Something like this:

module Paperclip
  class FileCommandContentTypeDetector
    private

    def type_from_file_command
      # -- original code --
      # type = begin
        # # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.
        # Paperclip.run("file", "-b --mime :file", :file => @filename)
      # rescue Cocaine::CommandLineError => e
        # Paperclip.log("Error while determining content type: #{e}")
        # SENSIBLE_DEFAULT
      # end

      # if type.nil? || type.match(/\(.*?\)/)
        # type = SENSIBLE_DEFAULT
      # end
      # type.split(/[:;\s]+/)[0]

      # -- new code --
      type = begin
        Paperclip.run('file', '-b --mime :file', file: @filename)
      rescue Cocaine::CommandLineError
        ''
      end

      if type.blank?
        type = begin
          Paperclip.run('mimetype', '-b :file', file: @filename)
        rescue Cocaine::CommandLineError
          ''
        end
      end

      if type.blank? || type.match(/\(.*?\)/)
        type = SENSIBLE_DEFAULT
      end
      type.split(/[:;\s]+/)[0]
    end
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.