Priyank Dey Priyank Dey - 6 months ago 35
Ruby Question

How can I download the particular file which is uploaded using carrierwave?

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.
enter image description here

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"

Answer

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 %>