Stop file write if file size exceeds 500KB ruby on rails

倖福魔咒の 提交于 2019-12-06 14:32:33

问题


How can I stop file writing ( upload form remote url ) when file size exceeds 500KB ?

I am using following code to upload a remote file

require 'open-uri'
open('temp/demo.doc', 'wb') do |file|
  file << open('http://example.com/demo.doc').read
end

this code is working properly and I am able to get files in temp folder. Now I want if filesize exceeds 500KB then it should stop writing file. In other words I want only 500KB of file if it is more than 500KB


回答1:


IO#read, takes a bytes argument, so you can specify the size of what you want to read from IO as below:

require 'open-uri'
open('temp/demo.doc', 'wb') do |file|
  file << open('http://example.com/demo.doc').read(500000)
end

you can also play with things like file.stat.size but given you are piping directly to file you would have to do more things to get this to work.



来源:https://stackoverflow.com/questions/31639004/stop-file-write-if-file-size-exceeds-500kb-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!