【问题标题】:Rails FTP downloading images: too many files openRails FTP下载图像:打开的文件太多
【发布时间】:2013-07-06 01:23:24
【问题描述】:

我知道在打开文件而不关闭文件时会出现“打开的文件过多”错误,但尽管这样做(我认为)我仍然收到此错误:

remote_photos_list do |remote_path|
  Net::FTP.open(ip, username, password) do |ftp|
    tmp_path = File.join('tmp/images', File.basename(remote_path))
    ftp.getbinaryfile(remote_path, tmp_path)
    File.open(tmp_path, 'r') do |file|
      listing.photos.create(:image => file)
    end
    File.delete(tmp_path)
  end
end

错误发生在第一次迭代的listing.photos.create(:image => file) 行。

我尝试以相反的顺序嵌套最外层的块,改为通过 HTTP 下载,然后重新启动我的机器(这是在本地发生的),但都无济于事。从我在 StackExchange 和 Google 上看到的情况来看,这似乎应该是一个非常简单的问题,但我就是无法摆脱这个错误。

这发生在 Mac OS X 上的本地 Rails 3.2.13 服务器上,listinghas_many :photosListing 模型的一个实例,其中Photo 有一个名为image 的回形针附件,如果有任何帮助的话。

我也不知道tmp_file这一代是否必要;如果有解决办法,请告诉我,因为它可能会有所帮助。

再次,如果这是一个愚蠢的问题,我很抱歉,但我非常感谢任何帮助!

【问题讨论】:

  • 也许你可以尝试在循环之前打开文件一次并在每次迭代中使用它(每次都清空它)

标签: ruby-on-rails image ftp ruby-on-rails-3.2 paperclip


【解决方案1】:

将每个打开的文件嵌套在 begin…rescue 块中就可以了:

remote_photos_list do |remote_path|
  tmp_path = File.join('tmp/images', File.basename(remote_path))
  begin
    Net::FTP.open(ip, username, password) do |ftp|
      ftp.getbinaryfile(remote_path, tmp_path)
      File.open(tmp_path, 'r') do |file|
        listing.photos.create(:image => file)
      end
    end
    Rails.logger.info "File #{remote_path} download succeeded"
  rescue
    Rails.logger.info "File #{remote_path} download FAILED"
    #***try something else***
  ensure
    File.delete(tmp_path) if File.exist?(tmp_path)
  end
end

我不确定这是因为某些文件太大还是其他原因,但我想begin…rescue 块对于处理远程文件几乎总是必要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 2012-05-09
    • 2011-07-18
    • 2019-10-30
    • 2011-01-03
    相关资源
    最近更新 更多