首页 文章

通过回形针从URL保存图像

提问于
浏览
116

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

7 回答

  • 14

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

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

    这比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"
    
  • 3

    首先将带有 curb gem的图像下载到 TempFile ,然后只需分配tempfile对象并保存模型 .

  • 16

    这是一个简单的方法:

    require "open-uri"
    
    class User < ActiveRecord::Base
      has_attached_file :picture
    
      def picture_from_url(url)
        self.picture = open(url)
      end
    end
    

    那简单地说:

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

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

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

    我的回形针版本是4.2.1

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

  • 152

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

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

    在模型中

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

    因为那些旧的答案在这里是一个更新的:

    Add Image Remote URL to your desired Controller in the Database

    $ 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
    

    *在Rails4中,您必须在Controller中添加attr_accessible .

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

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

    这是一个硬核方法:

    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)
    

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

相关问题