How can I download a file from a URL and save it in Rails?
Try this:
require 'open-uri'
open('image.png', 'wb') do |file|
file << open('http://example.com/image.png').read
end
How can I download image from URL in rails using and save it to local disk(computer)?
Try with this
ImagesController
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
Create a new file in your images viewget_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.
Edit:
To get current folder path
pwd
rails download file from public folder
Instead of adding path in direct link, create one action which download the file from public folder.
routes.rb
get 'download_apk'
in your controller add below action which downloads apk file
def download_apk
send_file("#{Rails.root}/public/App.apk")
end
Rails: How to to download a file from a http and save it into database
Use open-url (in the Ruby stdlib) to grab the files, then use a gem like paperclip to store them in the db as attachments to your models.
UPDATE:
Attachment_fu does not accept the raw bytes, it needs a "file-like" object. Use this example of a LocalFile along with the code below to dump the image into a temp file then send that to your model.
http = Net::HTTP.new('www.google.com')
http.start() { |http|
req = Net::HTTP::Get.new("/intl/en_ALL/images/srpr/logo1w.png")
response = http.request(req)
tempfile = Tempfile.new('logo1w.png')
File.open(tempfile.path,'w') do |f|
f.write response.body
end
attachment = Attachment.new(:uploaded_data => LocalFile.new(tempfile.path))
attachement.save
}
Related Topics
How to Match All Occurrences of a Regex
What Does @@Variable Mean in Ruby
How to Use Ruby to Colorize the Text Output to a Terminal
Printing the Source Code of a Ruby Block
How to Modify Path For Homebrew
Tzinfo::Datasourcenotfound Error Starting Rails V4.1.0 Server on Windows
Rails Has_Many :Through Find by Extra Attributes in Join Model
How to Break Out from a Ruby Block