Rails: How to to Download a File from a Http and Save It into Database

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
}

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 to download an uploaded stored file from the database in rails?

resources :resumes do
get :download, on: :member
end

Will give you an idiomatically correct REST route:

resumes/:id/download

Change your link to:

<%= link_to "Download", download_resume_path(@resume), "data-turbolinks" => false %>

See Rails Routing from the Outside In - Adding More RESTful Actions.

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 view
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.

Edit:
To get current folder path

pwd

How to download binary files from a database in Rails?

You can initiate a download with the send_data controller method. Docs here: http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_data

So let's say you create a route for your download action:

get '/items/:id/download', as: :item_download

And provide your users with a link to your items:

link_to 'Download', item_download_path(@item), disable_with: 'Downloading...'

Now your controller initiates the download to the user:

def download
item = Item.find params[:id]

send_data item.file, filename: item.name, type: 'zip', disposition: 'attachment'
end

As soon as the user clicks the Download link it will grey out and change to Downloading... then the browser will open its download dialog and begin downloading the zip file.

Note: I assumed your item has a name method but it can be anything you want. The important options are type: 'zip', disposition: 'attachment'. Type is the file type and helps your browser know what it is and disposition is for the browser to either download the file or to render it on the page. For example if you're downloading a pdf file, passing disposition: 'inline' would make the browser display the pdf rather than download it directly.

How to serve a file for download from Rails?

You can use the send_file method, passing the path to the file as the first argument, as see in Rails documentation.

UPDATE

You can use a temporary file to save the CSV, like this:

require 'tempfile'

# automatically creates a file in /tmp
file = Tempfile.new('data.csv', 'w')
file.write('my csv')
file.close

send_file(file.path)

# remove the file from /tmp
file.unlink

UPDATE 2: AngularJS download

There are two ways to accomplish this: you can add a hidden href to download the file in the page and click it, or redirect the user to the Rails URL that sends the file when he clicks in the button. Note that the redirect will use parameters in the url, so it won't work well depending on the structure of query_box.

To add a hidden href to the page with the CSV:

$scope.csvSubmit = function() {
var csv = $.post('http://ip_addr:3000/api/csv', { 'input': $scope.query_box });
csv.done(function(result){
var hiddenElement = document.createElement('a');

hiddenElement.href = 'data:attachment/csv,' + encodeURI(result);
hiddenElement.target = '_blank';
hiddenElement.download = 'filename.csv';
hiddenElement.click();
})
}

To use the redirect:

$scope.csvSubmit = function() {
var url = 'http://ip_addr:3000/api/csv/?' + 'input=' + encodeURI($scope.query_box);
window.location = url;
}

How to save pictures from URL to disk

You are almost done. The only thing left is to store files. Let’s do it.

LOCATION = 'C:\pickaxe\pictures'
if !File.exist? LOCATION # create folder if it is not exist
require 'fileutils'
FileUtils.mkpath LOCATION
end

require 'net/http'
.... # your code with nokogiri etc.
links.each{|link|
Net::HTTP.start(PAGE_URL) do |http|
localname = link.gsub /.*\//, '' # left the filename only
resp = http.get link['src']
open("#{LOCATION}/#{localname}", "wb") do |file|
file.write resp.body
end
end
end

That’s it.

How to download a file from rails application

Don't use send_file with a parameter set by a user. This opens up a massive security hole, allowing a user to access any file that is readable by your application (namely, your entire application, but also possibly other files on the filesystem).

Rather, if the file is under public, link to the file itself. In your case:

<%= link_to "Raw blast output", "/data/02_blastout/#{@bl_file}" %>

No need for a special controller action.



Related Topics



Leave a reply



Submit