有人知道在下载文件时从ruby的Net :: FTP库获取状态更新的方法吗?我正在尝试实现一个Web界面,显示从远程ftp服务器下载文件时剩余百分比的进度条。
答案 0 :(得分:36)
为了将来的参考 - 我偶然发现了一个解决方案:
filesize = ftp.size(filename)
transferred = 0
p "Beginning download, file size: #{filesize}"
ftp.getbinaryfile(filename, "#{SOURCE_IMPORT_DIRECTORY}/#{filename}", 1024) { |data|
transferred += data.size
percent_finished = ((transferred).to_f/filesize.to_f)*100
p "#{percent_finished.round}% complete"
}
ftp.close
答案 1 :(得分:1)
我建立在@ smnirven的优秀方法上,通过100点进展来减少噪音:
filesize = ftp.size(filename)
transferred = 0
notified = false
ftp.getbinaryfile(filename, full_local_path, 1024) do |data|
transferred += data.size
percent_finished = (((transferred).to_f/filesize.to_f)*100)
if percent_finished.to_s.include?('.0')
print "." if notified == false
notified = true
else
notified = false
end
end
ftp.close
输出:
[progress] Downloading CBSA boundaries...
..........................................................................
..........................
[progress] Finished!
答案 2 :(得分:0)
只需对代码进行少量更新即可使输出更清晰。
filesize = ftp.size(FILENAME)
transferred = 0
percent_finished = -9999
ftp.gettextfile(FILENAME, File.basename(FILENAME)) { |data|
transferred += data.size
temp = (((transferred).to_f/filesize.to_f)*100).round
if percent_finished < temp
percent_finished = temp
STDOUT.write "\r Download progress: #{percent_finished.round}% completed"
end
}
ftp.close