如果文件大小超过500KB红宝石停止文件写入 [英] Stop file write if file size exceeds 500KB ruby on rails

查看:421
本文介绍了如果文件大小超过500KB红宝石停止文件写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用以下代码来上传远程文件

如何在文件大小超过500KB时停止文件写入
$ b $

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



<这个代码工作正常,我能够获取临时文件夹中的文件。现在我想如果文件大小超过500KB,那么它应该停止写文件。换句话说,如果文件大于500KB,我只需要500KB的文件。

解决方案

IO#read ,需要一个字节的参数,所以你可以指定你想要的大小从下面的IO中读取:

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

你也可以玩像 file.stat.size 的东西,但是如果你直接输入文件,你将不得不做更多的事情来实现这个功能。


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

解决方案

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.

这篇关于如果文件大小超过500KB红宝石停止文件写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆