实例私有方法
send_data(data, options = {}) Link
将给定的二进制数据发送到浏览器。此方法类似于 render plain: data,但还允许您指定浏览器应将响应显示为文件附件(即在下载对话框中)还是内联数据。您还可以设置内容类型、文件名等。
选项:¶ ↑
-
:filename- 建议浏览器使用的文件名。 -
:type- 指定 HTTP 内容类型。默认为application/octet-stream。您可以使用字符串或符号来表示已注册的类型(通过Mime::Type.register注册),例如:json。如果省略,类型将根据:filename中指定的文件扩展名推断。如果未为扩展名注册内容类型,将使用默认类型application/octet-stream。 -
:disposition- 指定文件将显示为内联还是下载。有效值为"inline"和"attachment"(默认)。 -
:status- 指定随响应发送的状态码。默认为 200。
通用数据下载
send_data buffer
下载动态生成的 tarball
send_data generate_tgz('dir'), filename: 'dir.tgz'
在浏览器中显示 Active Record 图像
send_data image.data, type: image.content_type, disposition: 'inline'
有关 HTTP Content-* 标头和缓存的更多信息,请参阅 send_file。
源代码: 显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/data_streaming.rb, line 122 def send_data(data, options = {}) # :doc: send_file_headers! options render options.slice(:status, :content_type).merge(body: data) end
send_file(path, options = {}) Link
发送文件。这通过 Rack::Sendfile 中间件使用服务器适用的方法(例如 X-Sendfile)。要使用的标头通过 config.action_dispatch.x_sendfile_header 设置。您的服务器也可以通过设置 X-Sendfile-Type 标头来配置此项。
如果 path 参数来自网页,请注意清理该参数。send_file(params[:path]) 允许恶意用户下载您服务器上的任何文件。
选项:¶ ↑
-
:filename- 建议浏览器使用的文件名。默认为File.basename(path)。 -
:type- 指定 HTTP 内容类型。您可以使用字符串或符号来表示已注册的类型(通过Mime::Type.register注册),例如:json。如果省略,类型将根据:filename中指定的文件扩展名推断。如果未为扩展名注册内容类型,将使用默认类型application/octet-stream。 -
:disposition- 指定文件将显示为内联还是下载。有效值为"inline"和"attachment"(默认)。 -
:status- 指定随响应发送的状态码。默认为 200。 -
:url_based_filename- 如果您希望浏览器从 URL 猜测文件名,请将其设置为true,这对于某些浏览器上的 i18n 文件名是必需的(设置:filename会覆盖此选项)。
默认的 Content-Type 和 Content-Disposition 标头设置为尽可能多地在浏览器中下载任意二进制文件。已知 IE 的 4、5、5.5 和 6 版本存在各种怪癖(尤其是在通过 SSL 下载时)。
简单下载
send_file '/path/to.zip'
在浏览器中显示 JPEG 图片
send_file '/path/to.jpeg', type: 'image/jpeg', disposition: 'inline'
在浏览器中显示 404 页面
send_file '/path/to/404.html', type: 'text/html; charset=utf-8', disposition: 'inline', status: 404
您可以使用其他 Content-* HTTP 标头来向客户端提供额外信息。有关 HTTP 标头的列表,请参阅 MDN 列表。
同时请注意,文档可能被代理和浏览器缓存。Pragma 和 Cache-Control 标头声明了文件如何被中间件缓存。它们默认要求客户端在释放缓存的响应之前与服务器进行验证。有关 Web 缓存的概述,请参阅 www.mnot.net/cache_docs/,有关 Cache-Control 标头规范,请参阅 RFC 9111。
源代码: 显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/data_streaming.rb, line 77 def send_file(path, options = {}) # :doc: raise MissingFile, "Cannot read file #{path}" unless File.file?(path) && File.readable?(path) options[:filename] ||= File.basename(path) unless options[:url_based_filename] send_file_headers! options self.status = options[:status] || 200 self.content_type = options[:content_type] if options.key?(:content_type) response.send_file path end