Stop file write if file size exceeds 500KB ruby on

2020-07-27 05:09发布

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条回答
一夜七次
2楼-- · 2020-07-27 05:54

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.

查看更多
登录 后发表回答