Rails从show action下载文件吗? [英] Rails download file from show action?
问题描述
我有一个允许您上传文档的上传器。我要做的是在查看文档的显示操作时触发该文档的下载。网址类似于:
I have an uploader which allows you to upload documents. What I want to do is trigger a download for the document when you view its show action. The url would be something like:
/documents/16
此文档可以是.txt或.doc。
This document could be .txt, or .doc.
到目前为止,我的表演动作如下:
So far, my show action looks like this:
def show
@document = Document.find(params[:id])
respond_with(@document) do |format|
format.html do
render layout: false, text: @document.name
end
end
end
我将如何实现这一目标?
How would I go about achieving this?
推荐答案
看看 send_data 方法:
将给定的二进制数据发送到浏览器。此方法类似于render:text => data,但是还允许您指定浏览器是将响应显示为文件附件(即在下载对话框中)还是内联数据。您还可以设置内容类型,外观文件名以及其他内容。
Sends the given binary data to the browser. This method is similar to render :text => data, but also allows you to specify whether the browser should display the response as a file attachment (i.e. in a download dialog) or as inline data. You may also set the content type, the apparent file name, and other things.
因此,我认为您的情况应该是像这样的东西:
So, I think in your case it should be something like this:
def show
@document = Document.find(params[:id])
send_data @document.file.read, filename: @document.name
end
这篇关于Rails从show action下载文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!