从不包含扩展名的网址获取文件扩展名

时间:2014-03-15 15:01:19

标签: ruby

例如:

https://www.gravatar.com/avatar/9784fd51f1db751e9806a0620f1c432b?s=32&d=identicon&r=PG

如果运行:

require 'open-uri'
local_path = 'app/assets/images/'

image_url = 'https://www.gravatar.com/avatar/9784fd51f1db751e9806a0620f1c432b?s=32&d=identicon&r=PG'
image_name = image_url.match( /[&=-_\w:]+$/i ).to_s;
image_content = open(image_url).read.to_s
# image_extension = File.extname(image_content) # doesn't work


puts image_content

File.open( local_path + image_name + '.jpg' , 'wb') do |out_file|
    out_file.write(image_content)
end

图片已成功保存,但我必须对“' .jpg”进行硬编码。连接到文件名的末尾(查看最后两行)。

目的是将'.jpg'替换为image_extension并使其仍然有效。

1 个答案:

答案 0 :(得分:0)

require "open-uri"
require "mime/types"

image_url = 'https://www.gravatar.com/avatar/9784fd51f1db751e9806a0620f1c432b?s=32&d=identicon&r=PG'
image_download = open(image_url)
type = MIME::Types[image_download.content_type]
extension = type[0].extensions[0]
# => "png"