当调用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
<<p> 视图/strong> <%= link_to 'Original Upload', download_path(name: @event_name,
batch: batch, file: batch_upload_filename(@event_name, batch)) %>
解决方案:这最终成为涡轮链接的一个已知问题。如果像我一样使用turbollinks 5,更新后的语法是:data: { turbolinks: false }
这最终成为涡轮链接的一个已知问题。如果像我一样使用turbollinks 5,更新后的语法是:
data: { turbolinks: false }
尝试设置处置:
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"
哦,不要在字符串中注入参数来构建下载路由。我可以注射"……//" into:name, "config", into:batch, "../config/database. ". Yml " into:file。将文件路径添加到模型。
make helper method
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))) %>