7

我有一个上传器,可以让你上传文件。我想要做的是在您查看文档的显示操作时触发文档的下载。网址将类似于:

/documents/16

该文档可以是 .txt 或 .doc。

到目前为止,我的表演动作如下所示:

  def show
    @document = Document.find(params[:id])
    respond_with(@document) do |format|
      format.html do
        render layout: false, text: @document.name
      end
    end
  end

我将如何实现这一目标?

4

2 回答 2

15

看一下send_data方法:

将给定的二进制数据发送到浏览器。此方法类似于render :text => data,但也允许您指定浏览器是否应将响应显示为文件附件(即在下载对话框中)或内联数据。您还可以设置内容类型、外观文件名和其他内容。

所以,我认为你的情况应该是这样的:

def show
  @document = Document.find(params[:id])
  send_data @document.file.read, filename: @document.name
end
于 2012-08-19T18:51:51.350 回答
3

我在控制器中创建了一个新方法来下载文件。它看起来像这样。Stored_File 是存档文件的名称,并有一个名为 stored_file 的字段,它是文件的名称。使用 Carrierwave,如果用户具有下载文件的访问/权限,则会显示 URL,然后使用 send_file 将文件发送给用户。

控制器

 def download
    head(:not_found) and return if (stored_file = StoredFile.find_by_id(params[:id])).nil?

    case SEND_FILE_METHOD
      when :apache then send_file_options[:x_sendfile] = true
      when :nginx then head(:x_accel_redirect => path.gsub(Rails.root, ''), :content_type => send_file_options[:type]) and return
    end
    path = "/#{stored_file.stored_file}"

    send_file path, :x_sendfile=>true

  end

看法

<%= link_to "Download", File.basename(f.stored_file.url) %>

路线

match ":id/:basename.:extension.download", :controller => "stored_files", :action => "download", :conditions => { :method => :get }
于 2012-08-19T18:52:59.577 回答