如何从URL下载Internet图像并将其保存在Rails的本地位置?

时间:2019-01-14 13:58:41

标签: ruby-on-rails ruby

如何从URL下载Internet图像并将其保存在Rails的本地?

如果提交表单,我会提供一个添加图像URL form link的表单,我想将图像下载到计算机本地磁盘(Home / Documents / food_img)

请帮助

在下载控制器中

class DownloadsController < ApplicationController
    def index
        @downloads = Download.all
        @download = Download.new
    end

    def create
        @download = Download.create(user_params)
    end

    private

    def user_params
        params.require(:download).permit(:image,:image_url)
    end
end

在view / index.html.erb

<%= form_for(@download, url: downloads_path) do |f| %>
<%= f.text_field :image_url %>
<%=f.submit%>
<% end %>

在模型中

class Download < ApplicationRecord
    has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

    require 'open-uri'
    download = open('http://www.shopprod.com/assets/photos/ishop-718755d2bc62956994c867681b2622e77b4c9af3d1ecd6fa856127b704a459b2.png')
    IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")
end

在数据库中

t.string: image_url

1 个答案:

答案 0 :(得分:1)

如果您正在使用ActiveStorage(我建议这样做),则可以使用.attach将IO流附加到记录。

给定:

class Download < ApplicationRecord
  has_one_attached :image
end

您可以从Rails控制台下载文件并将其附加为:

require 'open-uri'
uri = 'http://www.shopprod.com/assets/photos/ishop-718755d2bc62956994c867681b2622e77b4c9af3d1ecd6fa856127b704a459b2.png'
download = Download.new
download.image.attach(io: open(uri), filename: uri.split('/').last)

但是,您不能只是将它扔进模型类中并期望它能工作。读取类时,将执行类主体。

相反,您需要将其放入方法中并在正确的位置调用它。

class Download < ApplicationRecord
  has_one_attached :image
  def download_image!
    require 'open-uri'
    image.attach(
      io: open(self.image_url), 
      filename: self.image_url.split('/').last
    )
  end
end

class DownloadsController < ApplicationController
  def create
    @download = Download.new(download_params)
    if !@download.image.attached? && @download.image_url
      @download.download_image!
      # @todo handle errors 
    end
    if @download.save
      redirect_to @download
    else 
      render :new
    end
  end

  def download_params
    params.require(:download)
          .permit(:image, :image_url)
  end
end