Ruby-on-rails 通过回形针从 URL 保存图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4049709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:30:13  来源:igfitidea点击:

Save image from URL by paperclip

ruby-on-railsrubyuploadpaperclip

提问by khanh

Please suggest me a way to save an image from an URL by Paperclip.

请建议我一种通过 Paperclip 从 URL 保存图像的方法。

回答by Aditya Sanghi

In Paperclip 3.1.4 it's become even simpler.

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

def picture_from_url(url)
  self.picture = URI.parse(url)
end

This is slightly better than open(url). Because with open(url) you're going to get "stringio.txt" as the filename. With the above you're going to get a proper name of the file based on the URL. i.e.

这比 open(url) 稍微好一点。因为使用 open(url) 你会得到“stringio.txt”作为文件名。有了上面的内容,您将根据 URL 获得文件的正确名称。IE

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

self.picture_file_name    # => "avatar.png"
self.picture_content_type # => "image/png"

回答by Nicolas Blanco

Here is a simple way:

这是一个简单的方法:

require "open-uri"

class User < ActiveRecord::Base
  has_attached_file :picture

  def picture_from_url(url)
    self.picture = open(url)
  end
end

Then simply :

然后简单地:

user.picture_from_url "http://www.google.com/images/logos/ps_logo2.png"

回答by M?chael Makar?v

It didn't work for me until I used "open" for parsed URI. once I added "open" it worked!

直到我使用“open”来解析 URI,它才对我有用。一旦我添加了“打开”它就起作用了!

def picture_from_url(url)
  self.picture = URI.parse(url).open
end

My paperclip version is 4.2.1

我的回形针版本是 4.2.1

Before open it wouldn't detect the content type right, because it wasn't a file. It would say image_content_type: "binary/octet-stream", and even if I override it with the right content type it wouldn't work.

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

回答by Ariejan

First download the image with the curbgem to a TempFileand then simply assign the tempfile object and save your model.

首先将带有curbgem的图像下载到 a TempFile,然后简单地分配临时文件对象并保存您的模型。

回答by Mini John

As those are old Answer's here's a newer one:

由于这些是旧答案,因此这里有一个较新的答案:

Add Image Remote URL to your desired Controller in the Database

将图像远程 URL 添加到数据库中所需的控制器

$ rails generate migration AddImageRemoteUrlToYour_Controller image_remote_url:string
$ rake db:migrate

Edit your Model

编辑您的模型

attr_accessible :description, :image, :image_remote_url
.
.
.
def image_remote_url=(url_value)
  self.image = URI.parse(url_value) unless url_value.blank?
  super
end

*In Rails4 you have to add the attr_accessible in the Controller.

*在 Rails4 中,您必须在控制器中添加 attr_accessible。

Update your form, if you allow other to upload an Image from a URL

更新您的表单,如果您允许其他人从 URL 上传图片

<%= f.input :image_remote_url, label: "Enter a URL" %>

回答by prabu

It may helpful to you. Here is the code using paperclip and image present in remote URL .

它可能对你有帮助。这是使用远程 URL 中存在的回形针和图像的代码。

require 'rubygems'
require 'open-uri'
require 'paperclip'
model.update_attribute(:photo,open(website_vehicle.image_url))

In model

在模型中

class Model < ActiveRecord::Base
  has_attached_file :photo, :styles => { :small => "150x150>", :thumb => "75x75>" }
end

回答by Diego D

Into official documentation is reported here https://github.com/thoughtbot/paperclip/wiki/Attachment-downloaded-from-a-URL

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

Anyway it seems not updated, because in last version of paperclip something has changed and this line of code is no more valid:

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

user.picture = URI.parse(url)

It raise an error, in particular this error is raised:

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

Paperclip::AdapterRegistry::NoHandlerError: No handler found for #<URI:: ...

The new correct syntax is this one:

新的正确语法是这样的:

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

Also we need to add these lines into config/initializers/paperclip.rbfile:

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

Paperclip::DataUriAdapter.register
Paperclip::HttpUrlProxyAdapter.register

Tested this with paperclip version 5.3.0and it works.

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

回答by Martin Streicher

This is a hardcore method:

这是一个核心方法:

original_url = url.gsub(/\?.*$/, '')
filename = original_url.gsub(/^.*\//, '')
extension = File.extname(filename)

temp_images = Magick::Image.from_blob open(url).read
temp_images[0].write(url = "/tmp/#{Uuid.uuid}#{extension}")

self.file = File.open(url)

where Uuid.uuid just makes some random ID.

其中 Uuid.uuid 只是制作一些随机 ID。