module Roda::RodaPlugins::ResponseAttachment::ResponseMethods

  1. lib/roda/plugins/response_attachment.rb

Methods

Public Instance

  1. attachment

Public Instance methods

attachment(filename = nil, disposition='attachment')

Set the Content-Disposition to “attachment” with the specified filename, instructing the user agents to prompt to save.

[show source]
   # File lib/roda/plugins/response_attachment.rb
58 def attachment(filename = nil, disposition='attachment')
59   if filename
60     param_filename = File.basename(filename)
61     encoding = param_filename.encoding
62 
63     needs_encoding = param_filename.gsub!(/[^ 0-9a-zA-Z!\#$&\+\.\^_`\|~]+/, '-')
64     params = "; filename=#{param_filename.inspect}"
65 
66     if needs_encoding && (encoding == UTF8_ENCODING || encoding == ISO88591_ENCODING)
67       # File name contains non attr-char characters from RFC 5987 Section 3.2.1
68 
69       encoded_filename = File.basename(filename).force_encoding(BINARY_ENCODING)
70       # Similar regexp as above, but treat each byte separately, and encode
71       # space characters, since those aren't allowed in attr-char
72       encoded_filename.gsub!(/[^0-9a-zA-Z!\#$&\+\.\^_`\|~]/) do |c|
73         "%%%X" % c.ord
74       end
75 
76       encoded_params = "; filename*=#{encoding.to_s}''#{encoded_filename}"
77     end
78 
79     unless @headers[RodaResponseHeaders::CONTENT_TYPE]
80       ext = File.extname(filename)
81       if !ext.empty? && (content_type = Rack::Mime.mime_type(ext, nil))
82         @headers[RodaResponseHeaders::CONTENT_TYPE] = content_type
83       end
84     end
85   end
86 
87   @headers[RodaResponseHeaders::CONTENT_DISPOSITION] = "#{disposition}#{params}#{encoded_params}"
88 end