過去,我發現檢索遠程文件的最可靠方法是使用命令行工具「wget」。下面的代碼主要是從現有的生產直複製(Rails的2.X)的應用程序有一些調整,以適應您的代碼示例:
class CategoryIconImporter
def self.download_to_tempfile (url)
system(wget_download_command_for(url))
@@tempfile.path
end
def self.clear_tempfile
@@tempfile.delete if @@tempfile && @@tempfile.path && File.exist?(@@tempfile.path)
@@tempfile = nil
end
def self.set_wget
# used for retrieval in NrlImage (and in future from other sies?)
if [email protected]@wget
stdin, stdout, stderr = Open3.popen3('which wget')
@@wget = stdout.gets
@@wget ||= '/usr/local/bin/wget'
@@wget.strip!
end
end
def self.wget_download_command_for (url)
set_wget
@@tempfile = Tempfile.new url.sub(/\?.+$/, '').split(/[\/\\]/).last
command = [ @@wget ]
command << '-q'
if url =~ /^https/
command << '--secure-protocol=auto'
command << '--no-check-certificate'
end
command << '-O'
command << @@tempfile.path
command << url
command.join(' ')
end
def self.import_from_url (category_params, url)
clear_tempfile
filename = url.sub(/\?.+$/, '').split(/[\/\\]/).last
found = MIME::Types.type_for(filename)
content_type = !found.empty? ? found.first.content_type : nil
download_to_tempfile url
nicer_path = RAILS_ROOT + '/tmp/' + filename
File.copy @@tempfile.path, nicer_path
Category.create(category_params.merge({:icon => ActionController::TestUploadedFile.new(nicer_path, content_type, true)}))
end
end
rake任務的邏輯可能是:
[
['Cat', 'cat'],
['Dog', 'dog'],
].each do |name, icon|
CategoryIconImporter.import_from_url {:name => name}, "https://xyz.com/images/#{icon}.png"
end
這將使用MIME類型的寶石的內容類型的發現:
gem 'mime-types', :require => 'mime/types'
你試圖從其他網站獲取的圖像,具有某種問題,是嗎?爲什麼回形針的東西呢?你爲什麼不直接下載圖標並單獨上傳?你確實意識到回形針是否用於處理文件上傳,對嗎? – coreyward 2011-06-12 00:17:20
我想在回形針樣式中添加圖標。有大約400個圖標..我不可能創建大量的文件夾。 – 2011-06-12 06:33:30
@coreyward更多這些圖標與某些類別相關,每個類別都有很多其他細節。 – 2011-06-12 19:52:54