Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails how to create a multiple choice image upload

I want to create an image uploader. Where the user can either paste an url to an image that then gets uploaded or upload a image from their local computer. And how should I validate for the Image?

How do I create this with paperclip or, some other image upload gem?

My view:

<%= simple_form_for [:admin, @konkurrancer], :html => { :multipart => true } do |f| %>
    <%= f.input :name, :label => 'Titel', :style => 'width:500;' %>
    <%= f.file_field :photo, :label => '125x125', :style => 'width:250;' %> or 
    <%= f.input :photo, :label => '125x125', :style => 'width:500;' %>
    <%= f.button :submit, :value => 'Create item' %>
<% end %>
like image 451
Max Avatar asked Nov 18 '25 22:11

Max


1 Answers

here's an approach how you could realise an remote upload (and still using paperclip):

Create a class like this:

require 'open-uri'

# Make it always write to tempfiles, never StringIO
OpenURI::Buffer.module_eval {
  remove_const :StringMax
  const_set :StringMax, 0
}

class RemoteUpload 

  attr_reader :original_filename, :attachment_data

  def initialize(url) 
    # read remote data
    @attachment_data    = open(url)

    # determine filename
    path = self.attachment_data.base_uri.path

    # we need this attribute for compatibility to paperclip etc.
    @original_filename = File.basename(path).downcase
  end

  # redirect method calls to uploaded file (like size etc.)
  def method_missing(symbol, *args)
    if self.attachment_data.respond_to? symbol
      self.attachment_data.send symbol, *args
    else
      super
    end
  end

end

Edit

You could add a virtual attribute like photo_remote_url to your Model:

class YourModel < ActiveRecord::Base 

  attr_accessor :photo_remote_url

  def photo_remote_url=(url) 
    return if url.blank?
    self.photo = RemoteUpload.new(url)
  end

end
like image 98
sled Avatar answered Nov 20 '25 13:11

sled



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!