Reputation: 1124
Hi I am using Ruby 2 and Rails 4. I am uploading a pdf file and its stored in public/uploads/contact/file/15/abc.pdf
because I am using CarrierWave, and in my file_uploader.rb the below code is written.
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
Now I want to download the same file which I uploaded. How can I download that file? Please share with me if anyone has any idea. I am adding my code below.
Showing picture what I want to do exactly. Choosing a file upload it and then download it.
My codes are:
downloads_form.html.erb
<table class="table table-condensed table-responsive">
<tbody>
<%= form_tag create_form_path, multipart: true do |f| %>
<tr>
<td>ABC</td>
<td><%= file_field_tag "contact[file]", class: "form-control" %></td>
<td><%= submit_tag 'Upload' %></td>
<td><%= link_to "Download", static_pages_downloadform_pdf_path %></td>
</tr>
<tr>
<td>DEF</td>
<td><%= file_field_tag "contact[file]", class: "form-control" %></td>
<td><%= submit_tag 'Upload' %></td>
<td><%= link_to "Download", static_pages_downloadform_pdf_path %></td>
</tr>
<% end %>
</tbody>
</table>
static_pages_controller.rb
def create_form
@form_downup = Contact.new(contact_params)
if @form_downup.save
redirect_to :back
else
render downloads_form_path
end
end
def downloadform_pdf
end
private
def contact_params
params.require(:contact).permit(:file)
end
routes.rb
match '/downloads_form', to: 'static_pages#downloads_form', via: 'get', as: :downloads_form
match '/create_form', to: 'static_pages#create_form', via: 'post', as: :create_form
get "static_pages/downloadform_pdf"
Upvotes: 1
Views: 1713
Reputation: 1124
Solved by this way.
def downloadform_pdf
file_type=params[:file_name]
contact = Contact.find_by_name(file_type)
actual_file_name=contact.file.to_s
file = File.join(Rails.root, 'public',actual_file_name)
send_file(file, filename: 'My-Form.pdf', type: 'application/pdf')
end
View:
<%= form_tag create_form_path, multipart: true do |f| %>
<td><%= text_field_tag "contact[name]", nil, value: "G_form", class: "form-control", :readonly => true %></td>
<td><%= file_field_tag "contact[file]", class: "form-control" %></td>
<td><%= submit_tag 'Upload' %></td>
<td><%= link_to "Download", static_pages_downloadform_pdf_path(:file_name => "G_form") %></td>
<% end %>
Upvotes: 1
Reputation: 931
I am adding a example, by looking on this you can solve your problem
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
Upvotes: 0