我需要调用方法 download_images("\folder","http:\url") 将来自 url 的图片保存在选择的目录中。这个方法应该在 index.html.erb 中调用,然后从 textbox1 中获取文件夹地址,然后从 textbox2 中获取 url按下按钮 1。
现在我不知道如何从文本框中获取字符串,我正在尝试正确调用方法 index.html.erb 代码:
<h1>Welcome#index</h1>
<p><%= "Download pictures from url!" %></p>
<div class="form-horizontal">
<p> Input url: </p>
<p> <input type="text"/> </p>
<p> Input destination folder: </p>
<p> <input type="text"/> </p>
<button class="btn">Go!</button>
<% button_to "btn", :method=> download_images("`/tutorial1/downloadedpics","http://www.yandex.ru/") %>
</div>
我在welcome_controller.rb 中定义了方法download_images:
class WelcomeController < ApplicationController
def index
end
def download_images(url, destination_path, options = {})
base_url = URI.join(url, "/").to_s
body = Typhoeus::Request.get(url).body
imgs = Nokogiri::HTML(body).css("img")
image_srcs = imgs.map { |img| img["src"] }.compact.uniq
hydra = Typhoeus::Hydra.new(:max_concurrency => options[:max_concurrency] || 50)
image_paths = image_srcs.map do |image_src|
image_url = URI.join(base_url, image_src).to_s
path = File.join(destination_path, File.basename(image_url))
request = Typhoeus::Request.new(image_url)
request.on_complete { |response| File.write(path, response.body) }
hydra.queue(request)
path
end
hydra.run
image_paths
end
end
在我切换服务器并转到 localhost 后,我收到一个异常:NoMethodError in Welcome#index, undefined method download_images' for #<#<Class:0x007f202fc3ae50>:0x007f202f9ab518>, in line <% button_to "btn", :method=> download_images("
/tutorial1/downloadedpics"," http://www.yandex.ru/ ") %>
我是一个菜鸟程序员,所以我可以犯相当愚蠢的错误......而且重要的是要提到:我在 Nitrous web box 工作,并不知道是否可以在 box 文件夹中下载图像:
~/tutorial1/downloadedpics
我还使用 Bootstrap 控制器、Nokogiri gem 和 Typhoeus gem。
Ruby 版本:ruby 2.1.1p76 Rails 版本:Rails 4.1.0 感谢您的关注。