我有一个表格来添加图片 url form , 如果用户添加图片 url 我想下载图片并保存到本地磁盘(home/documents/image)
我创建图像模型和 Controller ..
需要帮助
在图像模型中
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
在图像 Controller 中
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
最佳答案
试试这个
图像 Controller
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
在 ImageView 中创建一个新文件
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'
Note: If you want to give different name to images make a method and pass it at image name and modify code (action name and files) according to your need.
编辑: 获取当前文件夹路径
密码
关于ruby-on-rails - 如何使用 rails 从 URL 下载图像并将其保存到本地磁盘(计算机)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54284955/