【问题标题】:How can I download image from URL in rails using and save it to local disk(computer)?如何使用 Rails 中的 URL 下载图像并将其保存到本地磁盘(计算机)?
【发布时间】:2019-06-14 13:07:58
【问题描述】:

我有一个表格来添加图片网址form, 如果用户添加图片 url 我想下载图片并保存到本地磁盘(home/documents/image)

我创建图像模型和控制器..

需要帮助

在图像模型中

class Image < ApplicationRecord

    has_one_attached :image
    require 'open-uri'
    image = open('http://example.com/image.png')
    IO.copy_stream(image, '~/home/Documents/Images/local_image.png')

end

在图像控制器中

class ImagesController < ApplicationController 

    def index
      @image = Image.new
    end

end

在图片/index.html.erb中

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

但出现错误

OpenURI::HTTPError in ImagesController#index 404 not found

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

试试这个

图像控制器

require 'open-uri'

def get_image_url
end

def download_image
  read_image = open(params[:image_url]).read
  File.open('/home/documents/image/image.png', 'wb') do |file|
    file.write read_image
  end
  redirect_to root_path
end

在图像视图中创建一个新文件 get_image_url.html.erb

<%= form_tag("/images/download_image", method: "post") do  %>
  <%= label_tag :image_url %>
  <%= text_field_tag :image_url %>
  <%= submit_tag 'Download' %>
<% end %>

routes.rb

post 'images/download_image'
get 'images/get_image_url'

注意:如果您想为图像赋予不同的名称,请创建一个方法并将其传递到图像名称并根据需要修改代码(动作名称和文件)。

编辑: 获取当前文件夹路径

pwd

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    相关资源
    最近更新 更多