【问题标题】:Rails how to create a multiple choice image uploadRails 如何创建多选图片上传
【发布时间】:2011-08-27 09:10:27
【问题描述】:

我想创建一个图片上传器。用户可以将 URL 粘贴到然后上传的图像上,也可以从本地计算机上载图像。我应该如何验证图像?

如何使用回形针或其他图像上传 gem 创建它?

我的看法:

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 paperclip


    【解决方案1】:

    这是一种实现远程上传(仍然使用回形针)的方法:

    像这样创建一个类:

    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
    

    编辑

    你可以为你的模型添加一个像 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
    

    【讨论】:

    • 视图应该是什么样子的?我试图为我的回形针照片创建一个 file_field,为 url 创建一个 input_field,但我的照片的 input_field 没有出现在视图中。
    • 您可以编辑您的答案并发布带有输入字段的表单部分吗?
    • 出现输入字段,但它是文件上传字段
    • 好的,你试过f.text_field :photo 吗?如果您插入一个名为 photo_url 的新字段会更好,例如f.text_field :photo_url。如果 :photo 字段为空,则检查控制器,然后使用 :photo_url 字段
    • 我尝试过 text_field 它不起作用(输入与简单形式的 text_field 相同)我尝试添加 photo_url,但得到此错误未定义方法`photo_url'。我应该在我的模型中定义 photo_url 吗?
    猜你喜欢
    • 1970-01-01
    • 2012-09-28
    • 2018-02-12
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2013-05-31
    相关资源
    最近更新 更多