2014-03-26 107 views
0

我知道这已经被问过,但我找不到任何非常像我面临的问题。使用Paperclip从URL获取图像

我正在使用open()方法下载并保存文件。

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

这将引发一个错误:Paperclip error while determining content type 我发现这对SO,但我是一个Linux机器上,因此不适用于:

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

的另一种方式做,这是使用URI.parse()。不过,我之前遇到过问题,现在看起来工作正常。

总的来说,来自open()URI.parse()的行为是不可预知的。有时他们有时候工作,但他们没有。在这种情况下使用哪种最佳方案?我可以使用哪种失败安全策略?

+0

你有没有需要“开URI”在你的文件的顶部? – fengd

回答

2

我遇到过某些文件类型的类似问题。我使用Ubuntu 12.04和file --mime并不总能找到文件类型,例如.doc文件。

我通过修改回形针使用file --mime来解决这个问题,然后回到mimetype

事情是这样的:

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