开发者

How to keep temp files over requests in Rails?

In my Rails application users can upload Excel files. In my model there is a class ImportFile that uses attachment_fu like this:

class ImportFile < ActiveRecord::Base
  has_attachment :storage => :file_system, :path_prefix => 'public/imports', :max_size => 10.megabytes
end

When user clicks "Add file" he enters a page with a <%= fields.file_field :uploaded_data %>. attachment_fu does it's job and file upload is being done (let's ommit validation problems). I want to keep this file for future so I copy uploaded file to other temp file. Temp file is working fine - I can see it on disk.

def self.write_to_tmp(data)
    temp_file = Tempfile.new("import", "#{Rails.root}/tmp")
  begin
    temp_file.write(data)
  ensure
    temp_file.close(false)
  end
  temp_file
end

What I want to do is to show user a preview and then let him choose if he wants to add a file or discard it - there are two buttons. I have a problem when user chooses to save a file, because开发者_StackOverflow中文版 a temp file I've just created above is gone. It is deleted before request.

Does anyone has hints how to achive this? Or can point me to upload-with-preview file scenario like the one I've presened? I've been looking for days, but I've failed to find one.


The most reliable approach to this sort of thing would be to create a simple "upload" tracking model like you have there, but using Paperclip instead. This can be configured to handle a very large number of files.

You need to actually save these records for them to persist between requests. This will lead to orphaned records, but a simple cron job or rake task you can kill off all the unused files any time you need to.

Creating a large number of files in a single directory is usually a bad idea. Paperclip has a path parameter which will split up your ID number into parts, so record #903132 goes into .../90/31/32 for example.

Keep a regular attachment, and if they want to discard it, delete it, otherwise use it. At some point later clean out all the unused attachments.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜