通过回形针从URL保存图像

kha*_*anh 119 ruby upload ruby-on-rails paperclip

请建议我使用Paperclip从URL保存图像的方法.

Adi*_*ghi 195

在Paperclip 3.1.4中,它变得更加简单.

def picture_from_url(url)
  self.picture = URI.parse(url)
end
Run Code Online (Sandbox Code Playgroud)

这比open(url)略胜一筹.因为使用open(url)你将得到"stringio.txt"作为文件名.有了上述内容,您将根据URL获取文件的正确名称.即

self.picture = URI.parse("http://something.com/blah/avatar.png")

self.picture_file_name    # => "avatar.png"
self.picture_content_type # => "image/png"
Run Code Online (Sandbox Code Playgroud)

  • 如果弃用后仍在使用回形针,则可能还需要确保已加载URI IO加载器:Paperclip :: UriAdapter.register(在配置中,或者如果需要,可以临时通过控制台) (5认同)
  • 来自paperclip wiki:https://github.com/thoughtbot/paperclip/wiki/Attachment-downloaded-from-a-URL我在控制台中成功运行它,该应用程序在heroku中. (3认同)
  • 仅供参考,对于S3网址,我仍然将`application/octet_stream`作为`content_type`. (3认同)

Nic*_*nco 154

这是一个简单的方法:

require "open-uri"

class User < ActiveRecord::Base
  has_attached_file :picture

  def picture_from_url(url)
    self.picture = open(url)
  end
end
Run Code Online (Sandbox Code Playgroud)

那简单地说:

user.picture_from_url "http://www.google.com/images/logos/ps_logo2.png"
Run Code Online (Sandbox Code Playgroud)

  • 如果你需要使用`update_attributes`将`picture_from_url`重命名为`picture_url =(value)`. (7认同)
  • 使用`open(url)`,文件名不准确,例如`open-uri20150106-10034-lpd5fm`而不是`ef3a601e_ef3d008b_ef3d0f7e.jpg`. (6认同)
  • 这可能是不安全的,因为用户可以调用`user.picture_from_url('/ etc/password')`.但在大多数情况下它可能都很好. (3认同)
  • 请参阅下面的答案,以获得更好的解 (3认同)

Mïc*_*röv 16

在我使用"open"解析URI之前,它对我不起作用.一旦我加上"开放"就行了!

def picture_from_url(url)
  self.picture = URI.parse(url).open
end
Run Code Online (Sandbox Code Playgroud)

我的回形针版本是4.2.1

在打开之前,它不会检测内容类型,因为它不是文件.它会说image_content_type:"binary/octet-stream",即使我用正确的内容类型覆盖它也不行.


Ari*_*jan 15

首先将带有curbgem 的图像下载到a TempFile,然后简单地分配tempfile对象并保存模型.

  • 我没有看到这个答案出了什么问题,投了票,因为我看到了投票结果. (2认同)

Die*_*o D 5

进入官方文档在这里报道https://github.com/thoughtbot/paperclip/wiki/Attachment-downloaded-from-a-URL

无论如何它似乎没有更新,因为在上一个版本的回形针中有些东西已经改变,这行代码不再有效:

user.picture = URI.parse(url)
Run Code Online (Sandbox Code Playgroud)

它引发了一个错误,特别是引发了这个错误:

Paperclip::AdapterRegistry::NoHandlerError: No handler found for #<URI:: ...
Run Code Online (Sandbox Code Playgroud)

新的正确语法是这样的:

url = "https://www.example.com/photo.jpeg"
user.picture = Paperclip.io_adapters.for(URI.parse(url).to_s, { hash_digest: Digest::MD5 })
Run Code Online (Sandbox Code Playgroud)

我们还需要将这些行添加到config/initializers/paperclip.rb文件中:

Paperclip::DataUriAdapter.register
Paperclip::HttpUrlProxyAdapter.register
Run Code Online (Sandbox Code Playgroud)

用回形针版本对此进行了测试,5.3.0并且可以正常工作。