过去,我发现检索远程文件的最可靠方法是使用命令行工具“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