2015-05-18 30 views
2

我創建一個非常簡單的Web應用程序,允許用戶上傳的.zip文件,我暫時保存在我的應用程序內tmp的文件夾,使用壓縮文件解析的內容,然後刪除文件完成後。的Rails:權限遭拒,File.delete

我設法要上傳的文件,並將其複製到tmp文件夾,我可以成功地分析它,並得到我想要的結果,但是當我嘗試刪除該文件,我得到一個權限被拒絕的錯誤。

這裏是我的觀點:

<%= form_tag({action: :upload}, multipart: true) do %> 
    <%= file_field_tag :software %> 
    <br/><br/> 
    <%= submit_tag("UPLOAD") %> 
<% end %> 

這是我的控制器:

def upload  
    @file = params[:software] 
    @name = @file.original_filename 

    File.open(Rails.root.join('tmp', @name), 'wb') do |file| 
    file.write(@file.read) 
    end  
    parse 
    File.delete("tmp/#{@name}") 
    render action: "show" 
end 

我一直在使用FileUtils.rm ("tmp/#{@name}")也嘗試過了,我也試着刪除過,但都無濟於事設置File.chmod(0777, "tmp/#{@name}")。將刪除路徑更改爲Rails.root.join('tmp', @name)(如File.open塊)也不能解決問題。我可以通過控制檯完全刪除文件,所以我不知道可能是什麼問題。

編輯:parse方法:

def parse 
    require 'zip' 
    Zip::File.open("tmp/#{@nome}") do |zip_file| 
    srcmbffiles = File.join("**", "src", "**", "*.mbf") 
    entry = zip_file.glob(srcmbffiles).first 
    @stream = entry.get_input_stream.read 
    puts @stream 
    end 
end 

回答

2

問題是由於某種原因,我的文件沒有在File.open塊或Zip::File.open塊中被刪除。我的解決辦法是手動關閉,並避免使用開放式街區,改變這個片斷:從這個

f = File.open(Rails.root.join('tmp', @nome), 'wb+') 
f.write(@file.read) 
f.close 

,並改變了我的解析方法:

File.open(Rails.root.join('tmp', @name), 'wb') do |file| 
    file.write(@file.read) 
end  

這個

def parse 
    require 'zip' 
    Zip::File.open("tmp/#{@nome}") do |zip_file| 
    srcmbffiles = File.join("**", "src", "**", "*.mbf") 
    entry = zip_file.glob(srcmbffiles).first 
    @stream = entry.get_input_stream.read 
    puts @stream 
    end 
end 

到這個:

def parse 
    require 'zip' 
    zf = Zip::File.open("tmp/#{@nome}") 
    srcmbffiles = File.join("**", "src", "**", "*.mbf") 
    entry = zf.glob(srcmbffiles).first 
    @stream = zf.read(entry) 
    puts @stream 
    zf.close()  
end 

Noti我改變了我填充@stream的方式,因爲顯然entry.get_input_stream也會鎖定您正在訪問的文件。

1

寫入過程可以是靜止的鎖定該文件。您可能需要等到該過程完成。

+0

我只是想刪除前把'睡眠(30)'的權利,它仍然沒有好。是否有更正確的方法來等待寫作過程完成? – bpromas

+0

確保文件在解析過程後關閉。 30毫秒可能沒​​有足夠的時間......你可能需要一個循環幾次,直到該文件系統與文件 –

+0

這'sleep'功能在幾秒鐘內完成等待,使爲30秒......而我的'File.open '塊在結束時關閉文件,所以我不認爲這是不幸的。 – bpromas

1

' 「TMP /#{@名}」' 是不正確的路徑。只需使用'Rails.root.join'('tmp',@name)'

+0

似乎是這樣,是的,但即使改變了路徑也會發生同樣的錯誤。 – bpromas

+1

你能否提供「解析」方法? – moofkit

+0

當然。編輯它。它在我的.zip中找到一個特定的文件,並將它的內容放入一個變量中。它工作正常,我以爲它會關閉在結束'郵編:: File.open'塊 – bpromas