2016-08-24 39 views
0

当send_file被调用时,它将文件发送到浏览器,但浏览器将内容作为纯文本转储到新页面上,而不是下载文件。如果我刷新该页面,则会正常下载文件。Rails将send_file呈现文件作为纯文本在新页面上而不是浏览器下载文件

路线

get 'download' => 'qr_codes#download' 

控制器

def download 
    path = Rails.root.join("events/active/#{params[:name]}/#{params[:batch]}/#{params[:file]}") 
    send_file(path, type: 'application/vnd.ms-excel', filename: params[:file]) 
end 

查看

<%= link_to 'Original Upload', download_path(name: @event_name, 
    batch: batch, file: batch_upload_filename(@event_name, batch)) %> 

解决方案: 这最终成为known issue turbolinks。如果使用Turbolinks 5像我,更新的语法是:data: { turbolinks: false }

回答

1

尝试设置的配置:

def download 
    path = Rails.root.join("events/active/#{params[:name]}/#{params[:batch]}/#{params[:file]}") 
    send_file(path, type: 'application/vnd.ms-excel', filename: params[:file], disposition: 'attachment') 
end 

或更改文件,以确保扩展名是正确的

"#{params[:file][0,params[:file].index(".")]}.xlsx" 

哦,唐不会将params注入字符串以构建下载路径。我可以将“../../”注入到:name,“config”中,写入:batch,并将“../config/database.yml”注入到:file中。将文件路径添加到模型。

+0

处置默认为 '附件' 更新链接。我试图设置它,并且遇到了相同的结果。我也确保文件扩展名是根据您的建议正确的,并得到相同的结果。 –

+0

如果我直接去这里,它只会下载罚款'“http:// localhost:3000/download?batch = 1&file = HSS.xls&name = HSS + 2016”',只有当我从不同页面链接到此路径时,在浏览器中显示纯文本,然后像我在文章中提到的那样,刷新纯文本页面,然后将该文件正常下载。 –

+0

编辑我的帖子上面,我解决了这个问题。 –

2

这最终成为了turbolinks的一个已知问题。如果使用Turbolinks 5像我,更新的语法是:

data: { turbolinks: false } 
0

化妆辅助方法,

def some_helper(content_type) 
Rack::Mime::MIME_TYPES.invert[content_type].gsub(/\./mi, '') 
end 

<%= link_to 'Original Upload', download_path(name: @event_name, batch: batch, file: batch_upload_filename(@event_name, batch, format: file_format(attachment.file.content_type))) %> 
相关问题