【问题标题】:Sinatra send_file gives 404 error when trying to store the fileSinatra send_file 在尝试存储文件时出现 404 错误
【发布时间】:2021-01-18 21:36:16
【问题描述】:

我正在尝试使用邮递员模拟下载文件

响应 127.0.0.1 - - [18/Jan/2021:03:54:47 -0800] "POST / HTTP/1.1" 404 - 4.4450

命令 send_file "#{filename}", :disposition=> "attachment", :filename => filename, :type => 'application/octet-stream'

post '/' do
  fileSize = env['CONTENT_LENGTH'].to_i/1048576.0 # Converting to MB
  if params.has_key?(:file) && fileSize <= 1
    filename = params['file']["filename"]
    send_file "#{filename}", :disposition=> "attachment", :filename => filename, :type => 'application/octet-stream'
    puts ".......................FILE STORED........................."
  else
    puts "....................FILE NOT VALID........................."
  end  
end

【问题讨论】:

  • 可能是找不到文件。我会注销文件名 var 以检查查询参数中的设置是否正确。如果做不到这一点,我建议暂时忘记下载文件,看看您是否可以发布到该端点并获得 200 响应。这将确保下载文件而不是路由请求时出现问题。
  • 我可以得到以下文件信息&gt;{"filename"=&gt;"diet.txt", "type"=&gt;"text/plain", "name"=&gt;"file", "tempfile"=&gt;#&lt;Tempfile:/tmp/RackMultipart20210118-28539-1tmxeoh.txt&gt;, "head"=&gt;"Content-Disposition: form-data; name=\"file\"; filename=\"diet.txt\"\r\nContent-Type: text/plain\r\n"}
  • 文件确实存在?文件的路径是什么?
  • 是文件存在,路径是/home/mayuresh/Downloads/diet.txt
  • 你是如何运行rails的?是否在 fake_root 中(例如通过 Apache)?

标签: ruby http get sinatra


【解决方案1】:

在看到您对我的 cmets 的回复后,我可以说这不起作用的原因是因为 send_file 命令没有提供正确的参数。根据这些文档:https://apidock.com/rails/v2.3.8/ActionController/Streaming/send_file - 您必须附加文件路径作为第一个参数,而不仅仅是文件名。

此外,文件的位置(您的下载文件夹)可能会导致其他问题。该文件应该在您的项目目录中的某处可用,最好是在/public 文件夹中。

总结一下:

  • 将文件移动到项目中的/public 目录。
  • 在文件名前加上存储文件的路径。

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2020-07-09
    相关资源
    最近更新 更多