2014-03-26 101 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