Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carrierwave image extensions

I'm trying to determine whether a remote url is an image. Most url's have .jpg, .png etc...but some images, like google images, have no extension...i.e.

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSbK2NSUILnFozlX-oCWQ0r2PS2gHPPF7c8XaxGuJFGe83KGJkhFtlLXU_u

I've tried using FastImage to determine whether a url is an image. It works when any URL is fed into it...

How could I ensure that remote urls use FastImage and uploaded files use the whitelist? Here is what have in my uploader. Avatar_remote_url isn't recognized...what do I do in the uploader to just test remote urls and not regular files.

  def extension_white_list
    if defined? avatar_remote_url && !FastImage.type(CGI::unescape(avatar_remote_url)).nil?
      # ok to process
    else # regular uploaded file should detect the following extensions
      %w(jpg jpeg gif png)
    end
  end
like image 861
user749798 Avatar asked Apr 08 '13 16:04

user749798


People also ask

How do I upload multiple images in rails?

A file can be uploaded to server in two ways, one we can send the image as base64 string as plain text and another one is using multipart/form-data . The first one is the worst idea as it sends the entire image as plain text.

What is CarrierWave gem?

This gem provides a simple and extremely flexible way to upload files from Ruby applications. It works well with Rack based web applications, such as Ruby on Rails.


1 Answers

if all you have to work with is a url like that you can send a HEAD request to the server to obtain the content type for the image. From that you can obtain the extension

require 'net/http'
require 'mime/types'

def get_extension(url)
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true if uri.scheme == 'https'
  request = Net::HTTP::Head.new(uri.request_uri)
  response = http.request(request)
  content_type = response['Content-Type']
  MIME::Types[content_type].first.extensions.first
end
like image 192
ffoeg Avatar answered Sep 30 '22 06:09

ffoeg