开发者

link to delete a file from a directory

开发者 https://www.devze.com 2023-02-14 09:37 出处:网络
In a rails 2.3.8 app i am trying to write a link in a view that passes the filename to the method in a controller that deletes a file from a directory. Haven\'t been able to get the syntax right. I\'v

In a rails 2.3.8 app i am trying to write a link in a view that passes the filename to the method in a controller that deletes a file from a directory. Haven't been able to get the syntax right. I've updated the code below to reflect Tobias' suggestions. It works, except for file names that have spaces in them.

In the documents_conroller.rb file is the following method:

def file_cleanup
  File.delete("#{RAILS_ROOT}/public/downloads/#{params[:filename].gsub /[^\.\w]/, ''}") 
  redirect_to :action => :index
end

In the view:

<% @fi开发者_开发技巧les.each do |f| %>
   <% str = f.gsub(/^.*\//, '') %>
   <tr>
      <td>
          <%=str%>
      </td>
      <td>
          <%= link_to "Del", file_cleanup_path(:filename => str) %>
      </td>
   </tr>
<% end -%>

In the routes file:

map.file_cleanup '/file_cleanup', :controller => 'documents', :action => 'file_cleanup'

Thanks for your help!


I think you're mixing up resource routes with named routes.

With a named route

Route:

map.file_cleanup '/file_cleanup', :controller => 'documents', :action => 'file_cleanup'

In the view, pass through the filename as a parameter to the link url:

link_to "Del", file_cleanup_path(:filename => str)

Then in the controller, use params[:filename] to get the value:

File.delete("#{RAILS_ROOT}/public/downloads/#{params[:filename].gsub /[^\.\w]/, ''}") 

With a resource route

In the route, add a new member method:

map.resources :documents, :member => { :file_cleanup => :get }

In the view, you use the link you have now:

link_to "Del", file_cleanup_document_path(str)

In the controller, use params[:id] to get the value:

File.delete("#{RAILS_ROOT}/public/downloads/#{params[:id]}") 

Warning:

As Dan points out, using a user modifiable value directly in File.delete is a really bad idea. Here's a link to the Rails guide on sanitizing filenames:

http://guides.rubyonrails.org/security.html#file-uploads

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号