Rails Errno::ENOENT: 保存上传时没有那个文件或目录

Rails Errno::ENOENT: No such file or directory when saving an upload

我的 Rails API.

遇到以下问题

我正在尝试将文件保存到临时目录中。我最初的假设是我应该能够将它保存到系统 /tmp 目录中,因为那是该目录的用途。所以我的 gallery_images_controller.rb:

中有以下代码
    def upload
        # set the upload
        upload = params[:qqfile].original_filename
        # we want to save files in tmp for now
        directory = "/tmp"
        ap(directory)
        # create the full path for where to save the file
        path = File.join(directory, upload)
        ap(path)
        # get the md5 of the file so we can use it as the key in the json response
        md5 = Digest::MD5.file(path).hexdigest
        # save the file
        File.open(path, "w+b") { |f| f.write(params[:qqfile].read) }
        # render the result with the md5 as the key and the filename and full path
        render json: {success: true, upload: {"#{md5}": {filename: upload, full_path: path}}}, status: 200
    end

当我发送带有文件的 post 请求时,出现以下错误:

{:error=>true, :message=>"Errno::ENOENT: No such file or directory @ rb_sysopen - /tmp/3Form-Museum-of-Science-25.jpg"}

我也试过将文件保存在Rails.root tmp文件夹中,得到同样的错误:

directory = "#{Rails.root}/tmp/"

{:error=>true, :message=>"Errno::ENOENT: No such file or directory @ rb_sysopen - /vagrant/tmp/3Form-Museum-of-Science-25.jpg"}

我也试过 w+bwb 模式都没有用。

Ruby (http://ruby-doc.org/core-2.2.3/IO.html#method-c-new) 的文档说如果文件不存在,ww+ 模式应该创建文件。这正是我想要它做的,但事实并非如此。

另外,我检查了文件夹的权限。如您所料,/tmp 文件夹有 777 个,rails 根目录 /vagrant/tmp 有 755 个,就像 rails 根目录中的所有其他文件夹一样。

请帮忙!


系统信息:

你应该 运行

File.open(path, "w+b") { |f| f.write(params[:qqfile].read) }

之前

md5 = Digest::MD5.file(path).hexdigest

只需交换这两行,以便在计算十六进制摘要之前创建文件

对于任何遇到同样问题的人,这里是我所做的修复工作。

我修复了 2 个问题来解决此问题:

  1. 我更改了这一行:

    File.open(路径, "w+b") { |f| f.write(参数[:qqfile].read) }

为此:

File.open(path, "w+b") { |f| f.write(path) }
  1. 将上面的行移动到上面 md5

所以现在我的上传功能是这样的:

def upload
        # set the upload
        upload = params[:qqfile].original_filename
        # we want to save files in tmp for now
        directory = "/tmp"
        # create the full path for where to save the file
        path = File.join(directory, upload)
        # save the file
        File.open(path, "w+b") { |f| f.write(path) }
        # get the md5 of the file so we can use it as the key in the json response
        md5 = Digest::MD5.file(path).hexdigest
        # render the result with the md5 as the key and the filename and full path
        render json: {success: true, upload: {"#{md5}": {filename: upload, full_path: path}}}, status: 200
end