简体   繁体   English

Ruby on Rails-不下载文件

[英]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. 如果您同时查看“ / download /:url /:type”和“ /download/system/candidatos/cvs/000/000/001/original/blank_CV_template_Microsoft_Word.doc”,则将其视为url和类型。 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 在标记链接中,仅传递CV ID并以您的下载方法进行处理

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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