Export CSV file (without changing the page) - ruby-on-rails

show.html.erb
<%= link_to "Export", {:action => :export}, :method => :post%>
record_controller.rb
def export
csv_file = CSV.generate({}) do |csv|
csv << #data_filtered.first.keys
#data_filtered.each do |hash|
csv << hash.values
end
end
send_data csv_file, :type => 'text/csv; charset=iso-8859-1; header=present', :disposition => "attachment; filename=tester1.csv"
end
I am wondering how to do this because #data_filtered is an instance variable sent to show.view but it no longer exists when I click export (this is the data i want to export to a .csv). Is there a way to pass this data through link_to? I am also anticipating the issue that this is going to change the view which I dont want to do.

Here are two basic approaches:
In your 'show' method, save what's in #data-filtered to your model. Then you can find it again in the 'export' method.
Or, you have to send it all down to the client, and the client will have to send it all back.

Related

How to download file with id params?

Hello I try to download a jpeg image on rails by verifying that the Post exists and by recovering its id in parameter.
I try something but i got a error... I show you:
def download
send_file '/public/uploads/posts/#image/image.jpg', :type => 'image/jpeg', :disposition => 'attachment', :x_sendfile => true
end
private
def set_image
#image = Post.find(params[:id])
end
In my controller I have to in my routes get download.
And my link_to is:
<%= link_to "Download", download_posts_path %>
But rails say to me "Couldn't find Post without an ID".
I don't understand why... He dont't have the id but I dont't know why ?
Assuming you use set_image in a before_action filter.
First you should pass the post instance or id to your route helper :
If your route takes a param e.g. /posts/:id/download :
<%= link_to "Download", download_posts_path(#post) %>
<%= link_to "Download", download_posts_path(#post.id) %>
If not you can pass it with a query parameter e.g. posts/download/?id=1
<%= link_to "Download", download_posts_path(id: #post.id) %>
Both solution will provide you a params[:id] in your controller. Otherwise params[:id] will be nil and find raises an error.
Then there's something wrong in the download action as #DileepNandanam pointed out. You're not using your Post instance (#image) at all, you're just passing send_file a string containing "#image", not the variable but just a string. You may want to use interpolation to build a valid path to your image. For example if your #image has a :name which could be "image.jpg" you would do it like this:
send_file "/public/uploads/posts/#{#image.name}"
Or you could name your images with the post id like 13.jpg then you'll do :
send_file "/public/uploads/posts/#{#image.id}.jpg"
Or even create separate forlders with post's ids :
send_file "/public/uploads/posts/#{#image.id}/image.jpg"
send_file "/public/uploads/posts/#{#image.image_file_name}/image.jpg", :type => 'image/jpeg', :disposition => 'attachment', :x_sendfile => true
The method image_file_name may varies depends on the attachment you have specified on model
A better way is to use the url for attachment like
send_file #image.image.url(:original)

How to create a file on users machine instead of creating in server and then to download using rails

I am working on to allow download an excel file with the below code:
login = Etc.getlogin
#dataFile = "C:/rails/#{login}data.csv"
csv1=CSV.open(#dataFile, 'w') do |csv|
$data.each do |eachrow|
csv << [eachrow.name+"#gmail.com"]
end
end
send_file(#dataFile, :filename => "#{login}data", :type => "application/csv")
Using the above code, I am able to create a file and write the data.
Instead of this, how do i write the data in csv and get downloaded into users machine instead of saving in local/server.
What you can do is generate a string with the CSV library, using CSV::generate instead of CSV::open.
Controller:
class DataController < ApplicationController
def download
respond_to do |format|
format.csv { send_csv_download }
end
end
private
def send_csv_download
string = CSV.generate do |csv|
#data.each { |row| csv << ["#{row.name}#gmail.com"] }
end
send_data string, filename: 'foo.csv', type: :csv
end
end
config/routes.rb:
get '/download', to: 'data#download'
View:
<%= link_to 'Download CSV', download_path(format: :csv) %>
Note: Obviously, I have no idea where you get your #data from, since it isn't specified in your question.

How to download file with send_file?

Can someone enlighten me how can I download file with send_file?
I have a file image.jpg inside app/assets/images. I've tried this in my controller:
def download
send_file ("#{Rails.root}/public/images/image.jpg")
end
def download
send_file ("#{Rails.root}/assets/images/image.jpg")
end
def download
send_file ("#{Rails.root}/images/image.jpg")
end
def download
send_file ("/public/images/image.jpg")
end
def download
send_file ("/assets/public/images/image.jpg")
end
def download
send_file ("/assets/images/image.jpg")
end
For each path it says:
ActionController::MissingFile in HomeController#download
Cannot read file 'some_path'
What could be a problem here? Thanks!
Try:
IMAGES_PATH = File.join(Rails.root, "public", "images")
def download
send_file(File.join(IMAGES_PATH, "image.jpg"))
end
In your view =>
<%= link_to "click here to download", signed_feeds_pdf_path(:feed_image_path => feed_image.feedimage.path), target: '_self' %>
In your controller =>
def pdf
file_name = params[:feed_image_path].split('/').last
#filename ="#{Rails.root}/public/uploads/feed_image/feedimage/#{file_name}"
send_file(#filename ,
:type => 'application/pdf/docx/html/htm/doc',
:disposition => 'attachment')
end
soo simple......
well, i suggest you to move your file to public folder. Anyway , do this
send_file(Rails.root.join('app' , 'assets', 'images', 'image.jpg'))
We need to specify the mine type so that it will cache.
send_file ("#{Rails.root}/public"+image.image_path), :type => "image/jpeg", :disposition => 'inline'
For anyone still looking for an answer, send_data and send_file won't work when responding to ajax calls. Instead, try submitting a form or using <a href=..> to call the controller method and download a file.

Rails download file from show action?

I have an uploader which allows you to upload documents. What I want to do is trigger a download for the document when you view its show action. The url would be something like:
/documents/16
This document could be .txt, or .doc.
So far, my show action looks like this:
def show
#document = Document.find(params[:id])
respond_with(#document) do |format|
format.html do
render layout: false, text: #document.name
end
end
end
How would I go about achieving this?
Take a look at the send_data method:
Sends the given binary data to the browser. This method is similar to render :text => data, but also allows you to specify whether the browser should display the response as a file attachment (i.e. in a download dialog) or as inline data. You may also set the content type, the apparent file name, and other things.
So, I think in your case it should be something like this:
def show
#document = Document.find(params[:id])
send_data #document.file.read, filename: #document.name
end
I created a new method in my controller for downloading a file. It looks like this. Stored_File is the name of the archived file and has a field called stored_file which is the name of the file. Using Carrierwave, if a user has the access/permissions to download the file, the URL will display and then send the file to the user using send_file.
Controller
def download
head(:not_found) and return if (stored_file = StoredFile.find_by_id(params[:id])).nil?
case SEND_FILE_METHOD
when :apache then send_file_options[:x_sendfile] = true
when :nginx then head(:x_accel_redirect => path.gsub(Rails.root, ''), :content_type => send_file_options[:type]) and return
end
path = "/#{stored_file.stored_file}"
send_file path, :x_sendfile=>true
end
View
<%= link_to "Download", File.basename(f.stored_file.url) %>
Routes
match ":id/:basename.:extension.download", :controller => "stored_files", :action => "download", :conditions => { :method => :get }

Rails; save a rendered views html content to file

I'm trying to create a view with a download link to download the html source?
#Peter 's solution worked for me. Here is a code sample:
View:
<%= link_to 'download this page', object_path(#object, :download => true) %>
Controller:
def show
# ...
if params[:download]
send_data(render_to_string, :filename => "object.html", :type => "text/html")
else
# render normally
end
end
You can use render_to_string instead of render, which will give you the page, then to download it use send_data.
More on render to string here, and more on send_data here.

Resources