2015-09-17 84 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 
    
    相關問題