简体   繁体   中英

Ruby on Rails - Not downloading file

I have this link for the download

<%= link_to "Curriculum Vitae", "/download/#{@user.candidato.cv.url}/#{@user.candidato.cv.content_type}" %>

if i did the bad way without the controller method the download works. But I read many posts on the internet saying it was a bad way to do it so I tried the good way.

This is my controller:

    def download
       send_file params[:url] , :type => params[:type], :x_sendfile => true
    end

and the routes

match '/download/:url/:type', to: 'users#download', via: 'get'

And when I click the link this shows:

No route matches [GET] "/download/system/candidatos/cvs/000/000/001/original/blank_CV_template_Microsoft_Word.doc"

I've searched everywhere and I can't seem to find anything. For the files and all I'm using Paperclip

your routes and method name is not matching. if you take a look into both "/download/:url/:type" and "/download/system/candidatos/cvs/000/000/001/original/blank_CV_template_Microsoft_Word.doc" which one it will consider as url and type. As per your match routes your link path should be something like this - "download/url/type".

Or you can also go with even simpler approach. In your link to tag just pass only the ID of CV and process it in your download method

match '/download/:id', to: 'users#download', via: 'get'

def download
   cv = Cv.find(params[:id])
   send_file cv.url , :type => cv.content_type, :x_sendfile => true
end

What did it for me:

Controller:

def download
    path = params[:url]
    send_file "#{path}.#{params[:format]}" , :type => params[:type], :x_sendfile => true
  end

The format was added because the path even though in the console it included the extension in the controller it never did.

View:

<%= link_to "Curriculum Vitae", :action => :download, :url => @user.candidato.cv.path, :type => @user.candidato.cv.content_type %>

Routes file:

match '/download/:url', to: 'users#download', via: 'get'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM