【问题标题】:Attach image in form from a url with Paperclip (Rails)使用 Paperclip (Rails) 从 url 以表单形式附加图像
【发布时间】:2016-02-24 01:34:42
【问题描述】:

在为桌面图像附件指定的表单中, 我想从 URL 附加表单中的文件(不添加新字段,想使用上面的附件表单进行附加)。这在 Rails 中首先是可能的吗?这就是我目前所处的位置。


目前,我正在使用 Paperclip 作为图像附件,并且能够通过以下方式获取文件:

image_url = URI.parse('http://www.flicker/image.png')

imageFile = open(URI.parse(image_url))

如果你调用 imageFile,它会输出:#

我已经在我的模型中设置了所有内容:
has_attached_file :image, :styles => { :medium => "300x300#", :thumb => "100x100#" }
validates_attachment_content_type :image, :content_type => /\Aimage/

控制器:

 @deal = current_user.deals.build(
     #fills out other fields as well but deleted them
     #attatch image to field
    image: imageFile
    )

但不幸的是,简单地为图像分配新操作:成为 imageFile 是行不通的。有什么帮助吗?

【问题讨论】:

    标签: ruby-on-rails paperclip


    【解决方案1】:

    我可能误解了您的需求,但最简单的方法是从表单中删除文件字段,而是使用attr_reader 作为图像 URL 的新字段。然后在您的模型中,对该字段中的值进行 URI.parse 调用,然后返回该值。

    所以你的交易模型看起来像

    class Deal < ActiveRecord::Base
      attr_reader :image_remote_url
      has_attached_file :image, :styles => { :medium => "300x300#", :thumb => "100x100#" } 
      validates_attachment_content_type :image, :content_type => /\Aimage/
    
      def image_remote_url=(url)
        self.image = URI.parse(url)
        @image_remote_url = url
      end
    end
    

    这样您可以允许选项、url 或文件上传。

    【讨论】:

    • 感谢您的回答。是的,我知道创建 2 个字段可以解决问题,一个 url 和一个选择文件附件,但我只是好奇我是否可以通过以下方式填写“选择文件”附件字段:1)从参数中获取图像 url [ :search] 2) 从参数下载图像文件 3) 然后将文件附加到表单中,而不必从我的桌面上选择它。这是一件很奇怪的事情,但我或多或少只是为了好玩而尝试解决它。​​
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多