2015-09-17 58 views
0

我的Rails API遇到以下问题。Rails Errno :: ENOENT:保存上传时没有这样的文件或目录

我想将文件保存到临时目录中。我最初的假设是我应该能够将它保存到系统/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。根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,并且轨根/vagrant/tmp有755个,就像轨根中的所有其他文件夹一样。

请帮忙!


系统信息:

  • 开发:流浪箱运行Ubuntu 14.04,麒麟和nginx的
  • PROD:亚马逊EC2上运行的Ubuntu 14.04,麒麟和nginx的

回答

1

你应该只运行

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

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

只是交换了两条线,使该文件摘要计算为它

+0

谢谢,朋友帮我解决了这个问题。我发布了我的答案,并且正确,因为我的页面已经刷新,我看到了你的答案,所以我接受了你的答案!再次感谢! – paviktherin

0

对于任何与此同样的问题使得它在这里一个十六进制之前创建的是我做过什么来解决它。

有2个问题,我固定在解决此问题:

  1. 我改变了这一行:

    File.open(路径, “W + B”){| F | f.write(PARAMS [:qqfile]。读取)}

向该:

File.open(path, "w+b") { |f| f.write(path) } 
  • 移至上方的线是以上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 
    
    相关问题