简体   繁体   English

使用回形针(URL)以URL形式附加图像

[英]Attach image in form from a url with Paperclip (Rails)

In a form designated for a desktop image attachment, 在为桌面图片附件指定的表单中, 在此处输入图片说明 I want to instead attach a file in the form from a URL(without adding a new field, want to attach using the attachment form above). 我想改为从URL附加表单中的文件(不添加新字段,而要使用上面的附件表单附加)。 Is this first and foremost possible within Rails? 在Rails中这首先是可能的吗? Here's where I'm at so far. 这是我到目前为止的位置。


Currently, I'm using Paperclip for image attachments and am able to get a file by using: 目前,我正在使用Paperclip作为图像附件,并且能够通过以下方式获取文件:

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

imageFile = open(URI.parse(image_url))

And if you were to call the imageFile it would output this: #< File : 0x007fad310ca238> 如果要调用imageFile,它将输出以下内容:#<File:0x007fad310ca238>

I've setup everything in my model: 我已经在模型中设置了所有内容:
has_attached_file :image, :styles => { :medium => "300x300#", :thumb => "100x100#" } has_attached_file:image,:styles => {:medium =>“ 300x300#”,:thumb =>“ 100x100#”}
validates_attachment_content_type :image, :content_type => /\\Aimage/ validates_attachment_content_type:image,:content_type => / \\ Aimage /

Controller: 控制器:

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

But unfortunately simply assigning in the new action for the image: to be an imageFile doesn't work. 但不幸的是,只是为图像分配了新的操作:成为imageFile不起作用。 Any help? 有什么帮助吗?

I might be misunderstanding what you need, but the easiest way is to remove the file field from your form and instead use an attr_reader for a new field which is the URL of the image. 我可能会误解您的需求,但是最简单的方法是从表单中删除文件字段,而将attr_reader用于新字段,即图像的URL。 Then in your model, make your URI.parse call for the value in that field and then return that. 然后在模型中,对该字段中的值进行URI.parse调用,然后返回该值。

So your deal model would look something like 所以您的交易模型看起来像

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

This way you can allow either option, url or file upload. 这样,您可以上传选项,URL或文件。

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

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