【问题标题】:Rails: download file with "Open With" optionRails:使用“打开方式”选项下载文件
【发布时间】:2010-07-27 15:06:34
【问题描述】:

我正在运行 Rails 2.2.3。我有一个控制器用于管理上传和下载文件。我已成功链接到视图上的文件以允许用户下载,但是当下载对话框打开时,它只显示一个保存文件选项。我也想提供“打开方式”选项。我在 Ubuntu 10 上使用 Firefox 3.6。

这是用于将文件“发送”给用户的控制器:

def show

  @document = Document.find(params[:id])

  respond_to do |format|
    if File.exist?("#{RAILS_ROOT}/#{@document.path}")
      format.html { send_file "#{RAILS_ROOT}/#{@document.path}" }
    else
      flash[:error] = "File #{@document.path} does not exist!"
      format.html { redirect_to(:back) }
    end
  end

结束

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您应该设置正确的 MIME 类型(和扩展名)以允许 Firefox 识别正在下载的文件类型:

    send_file "#{RAILS_ROOT}/#{@document.path}", :type => "application/pdf",
      :filename => "document.pdf"
    

    您可以在文件上传时读取并存储此信息。

    uploaded_file.content_type  # the uploaded file's MIME type
    uploaded_file.original_path # name of the file
    

    即便如此,如果 MIME 类型未知,我认为您不会收到 Open with 提示。所以最终这也将取决于您在应用程序中使用的特定类型的文件。

    【讨论】:

    • 没有办法注册 Mime 类型吗?然后我可以注册我正在处理的所有不同文件,以便所有文件都有打开方式选项吗?
    • 没关系,我得到了 Mime 类型寄存器的工作——现在它适用于我所有的晦涩文件类型! :D
    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多