67

我正在使用 JPEGCAM 允许用户使用他们的网络摄像头拍摄个人资料照片。这会上传一个临时文件,如下所示:

def ajax_photo_upload    
  File.open(upload_path, 'w:ASCII-8BIT') do |f|
    f.write request.raw_post
  end
  # @user.photo = File.open(upload_path)
  @user.assign_attributes(
    :photo => File.open(upload_path),
    :orig_filename => "#{current_user.full_name}.jpg"
  )
  if @user.save
  respond_to do |format|
  .....
private

  def upload_path # is used in upload and create
    file_name = session[:session_id].to_s + '.jpg'
    File.join(::Rails.root.to_s, 'public', 'temp', file_name)
  end

安全删除此临时文件的最佳方法是什么?谢谢

4

2 回答 2

137

When you know that you are done with the file:

File.delete(path_to_file) if File.exist?(path_to_file)

Another thing: make sure that you always close files that you have opened, an operating system can only handle a certain number of open files/file descriptors and you'll may run into strange bugs when you pass that limit... So when you want to open files in Ruby always either use the block form:

File.open(path) do |f|
  # ...
end

and Ruby will close the file automatically for you. If the block form is not usable, you have to close files by yourself:

f = File.open(path)
# ...
f.close

So make sure to close the file that you pass to @user.assign_attributes(...)...

于 2012-10-10T08:14:41.293 回答
34

如果你确定你已经完成了它,为什么不直接使用FileUtils.rmor FileUtils.rm_f

FileUtils.rm_f(upload_path)

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-rm_f

您也可以在 Rails 中忽略这一点,并让 cron 唤醒并从与这些临时文件匹配的临时目录中删除超过一天的文件。如果文件无法重新处理 - 您不会立即对其进行 rm 处理 - 并且文件操作不是在 Rails 的请求/响应循环上完成的,那么这有一些错误余地的好处,这样会更快地响应。

于 2012-10-09T22:06:56.160 回答