开发者

Rails: download file with "Open With" option

开发者 https://www.devze.com 2023-01-09 03:52 出处:网络
I\'m running Rails 2.2.3. I have a controller that I am using to manage uploading and downloading files. I have successfully linked to files on the view to allow a user to download, but when the downl

I'm running Rails 2.2.3. I have a controller that I am using to manage uploading and downloading files. I have successfully linked to files on the view to allow a user to download, but when the download dialog box opens, it only shows a Save File option. I'd like 开发者_JAVA百科to have the "Open With" option available as well. I'm using Firefox 3.6 on Ubuntu 10.

This is the controller that is used to "send" the file to the user:

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

end


You should set the correct MIME type (and extension) to allow Firefox to recognise what kind of file is being downloaded:

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

You can read and store this information when the file is being uploaded.

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

Even then, if the MIME type is unknown, I don't think you'll get an Open with prompt. So ultimately this will also depend on the particular kinds of files you are using in your application.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号