Rails how to create multi-option image upload

I want to create an image downloader. If the user can insert the URL of the image, which then downloads or downloads the image from his local computer. And how should I check the image?

How to create this using paperclip or some other image?

My opinion:

<%= 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 %>
+3
source share
1 answer

here is how you could implement remote loading (and still using paperclip):

Create the class as follows:

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 can add a virtual attribute to your model, for example photo_remote_url:

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
+2
source

All Articles