简体   繁体   English

Rails如何创建多选图像上传

[英]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? 如何使用paperclip或其他图像上传宝石创建此文件?

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 %>

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: 您可以在模型中添加像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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM