gpt4 book ai didi

ruby-on-rails - Rails 使用 send_file 发送 0 字节文件

转载 作者:IT王子 更新时间:2023-10-29 00:15:34 24 4
gpt4 key购买 nike

我无法让 send_file(Model.attachment.path) 工作。它不会失败,相反,它会向客户端发送一个 0 字节大小的文件,但文件名是正确的。

在我从 Rails 2.3.8 大迁移到 3 之后,这个问题开始出现。

在这次迁移中还发生了很多其他事情,我会尽力详细说明所有这些事情。

  1. 分布变更/服务器变更。 Rackspace RHEL5 到 Linode Ubuntu 10.04LTS
  2. Ruby 版本变更,1.8.6 -> 1.9.2
  3. Rails 版本更改,2.3.8 -> 3.0.0
  4. httpd 平台更改,apache2 -> nginx(不过我也在 apache2 上尝试过,但没有成功)。

我通过 ftp 移动了附件,因为它们不是我的 git 存储库的一部分,所以它们是通过 cap deploy 发布的,而不是手动 ftp 远程(RHEL5)到本地(Win7)然后本地(Win7)到远程(Ubuntu10)。

我知道 FTPing 不会在传输过程中保留文件权限,所以我还做了模仿我以前服务器上看到的 chmod,因此它们几乎完全相同。 (用户/组不同,设置为root:root而不是olduser:olduser)。

从我的生产日志中下载附件的请求片段。

Started GET "/attachments/replies/1410?1277105698" for 218.102.140.205 at 2010-09-16 09:44:31 +0000
Processing by AttachmentsController#replies as HTML
Parameters: {"1277105698"=>nil, "id"=>"1410"}
Sent file /srv/app/releases/20100916094249/attachments/replies/UE0003-Requisition_For_Compensation_Leave.doc (0.2ms)
Completed 200 OK in 78ms

一切正常。让我也排除本地问题,我已经尝试在 Win7 和 Ubuntu(在 Vbox 上)上通过 Chrome 下载。

我也向您保证,路径确实是正确的。

root@li162-41:/srv/app/current# tail /srv/app/releases/20100916094249/attachments/replies/UE0003-Requisition_For_Compensation_Leave.doc
#
#
%17nw
HQ��+1ae����
%33333333333(��QR���HX�"%%��@9
��@�p4��#P@��Unknown������������G��z �Times New Roman5��Symbol3&�
�z �Arial5&�

所以总结一下这个问题,我如何让 send_file 真正发送文件而不是伪造的 0 字节垃圾。

最佳答案

send_file:x_sendfile 参数,在 Rails 3 中默认为 true。此功能通过返回带路径的 X-Sendfile header 的空响应,将流式下载卸载到前端服务器 - Apache(使用 mod_xsendfile)或 lighttpd。

Nginx 使用 X-Accel-Redirect header 来实现相同的功能,但您必须在适当的环境文件中正确配置 Rails:

config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'

Rails 3 更新:此行已存在于 production.rb 中,只需取消注释即可。

sendfile on; 添加到您的 nginx 配置以利用 Rails 发送的 header 。请记住必须使用绝对路径并且 nginx 必须具有对文件的读取权限。

别名文件的另一种方式:

为了更好的安全性,我在 nginx 中使用别名而不是绝对路径,但是 send_file 方法会检查是否存在使用别名失败的文件。因此,我将我的操作更改为:

  head(
'X-Accel-Redirect'=> file_item.location,
'Content-Type' => file_item.content_type,
'Content-Disposition' => "attachment; filename=\"#{file_item.name}\"");
render :nothing => true;

关于ruby-on-rails - Rails 使用 send_file 发送 0 字节文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3724853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com