我想从网上下载一些图片,但是有些网址没有指定文件扩展名,例如:
http://sportslabs-webproxy.imgix.net/http%3A%2F%2Fkty-platform-prod.silverchalice.co%2Fv3%2Fimages%2Fcontents%2F55bbe945e4b073340d3851fb?fit=clip&h=532&w=800&s=61b00197aca130a83de011484841158e
我打算使用“How do I download a picture using Ruby?”中提到的以下方法来下载文件,但正如我所说,我不确定如何告诉脚本将其保存为什么文件扩展名。
最佳答案
查看 ruby-filemagic gem 。
例如:
require 'open-uri'
require 'filemagic'
url = 'http://sportslabs-webproxy.imgix.net/http%3A%2F%2Fkty-platform-prod.silverchalice.co%2Fv3%2Fimages%2Fcontents%2F55bbe945e4b073340d3851fb?fit=clip&h=532&w=800&s=61b00197aca130a83de011484841158e'
open('raw_file', 'wb') do |file|
file << open(url).read
end
puts FileMagic.new(FileMagic::MAGIC_MIME).file( 'raw_file' )
# => 'image/jpeg; charset=binary'
更新:要找到保存文件的扩展名,您可以使用 mime-types
content_type = FileMagic.new(FileMagic::MAGIC_MIME).file( 'raw_file' ).split( ';' ).first
require 'mime/types'
puts MIME::Types[content_type].first.extensions.first
# => 'jpeg'
关于ruby - 在 Ruby 中,我如何知道托管在 Internet 上的图像文件的扩展名是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35139325/