0

短版(TLDR): 下面的 download_file 脚本在 Rails 3.2.6 中可以正常工作,但在 Rails 3.2.11 中不能。

长版:

我曾经有一个很好的下载文本文件功能,但现在当我尝试这个操作时,我得到了这个:

This webpage is not found 
No webpage was found for the web address: http://localhost:3000/file_download
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.

我的 routes.rb 指定了正确的 /file_download 路由。除了将我的 Rails 版本升级到 3.2.11 之外,我没有进行任何更改。我的下载脚本也没有改变;还是这样:

def download_file
    filename = 'my_memories.txt'
    file = File.open(filename, 'w') # creates a new file and writes to it

    current_user.memories.order('date DESC').each do |m|
      # Write the date, like 1/21/2012 or 1/21/2012~
      file.write m.date.strftime("%m/%d/%Y")
      file.write '~' unless m.exact_date
      file.write " #{m.note}" if m.note
      file.puts

      # Write the content
      file.puts m.content
      file.puts # extra enter
    end

    send_file file
    file.close # important, or no writing will happen
    File.delete(filename)
  end

我在控制台中看到的错误是这样的:

ERROR Errno::ENOENT: No such file or directory - my_memories.txt

而且我查看了Ruby 的 File.open 给出“没有这样的文件或目录 - text.txt (Errno::ENOENT)”错误并尝试了该解决方案,但这不起作用:我会得到一个不同的错误

private method `puts' called for #<String:0x00000104551838>

如果我这样做了

puts Dir.pwd.

在下载文件方法的开头。

可能出了什么问题?在 Rails 版本更改之前一切正常。

提前致谢。

4

1 回答 1

0

我找到了我的问题的答案,部分感谢这里的人:https ://github.com/rails/rails/issues/9086

基本上,send_file 之前被滥用过(我在网上某处看到了旧方法)。应该传递一个文件路径。

工作代码:

  def download_file
    filepath = "#{Rails.root}/public/downloaded_memories/my_memories.txt"

    file = File.open(filepath, 'w') # creates a new file and writes to it

    current_user.memories.order('date DESC').each do |m|
      # Write the date, like 1/21/2012 or 1/21/2012~
      file.write m.date.strftime("%m/%d/%Y")
      file.write '~' unless m.exact_date
      file.write " #{m.note}" if m.note
      file.puts

      # Write the content
      file.puts m.content
      file.puts # extra enter
    end

    send_file filepath # make sure to send the file path, not the file name
    file.close # important, or no writing will happen
    # File.delete(filepath) # cannot delete this since the request would not then try to send a file path that doesn't exist
  end
于 2013-01-27T03:55:49.987 回答