新手问题 Ruby 如何读取内存数据

feichan · 2013年05月27日 · 最后由 feichan 回复于 2013年05月28日 · 4394 次阅读

文件上传的时候,默认的是把图片分割成多份然后打包发送到 server 的内存中,待所有包都过来之后再写入硬盘上,那我怎么用 ruby 来读取内存中的每次发来的包数据呢?

你这个方案够怪异的,你可以试试先放入到 redis 中。ruby 内存当然可以放,但是不建议你这么搞。

#1 楼 @jimrokliu 我在写一上传图片的 api,post 一 file 到我这边,想发一个包接一个包,减少内存占用.redis 没试过,需要的时候可能会更长,想先用 ruby 这样实现一下。

发一个包缓存在内存里,又发一个包缓存在内存里,你都放在内存里能节省内存吗?

#3 楼 @jimrokliu 唔~~这是个问题哦,我再考虑一下吧。多谢了~!

#3 楼 @jimrokliu 那先不考虑内存问题。这样我想边接包边进行处理,比等它接收完成之后一次性处理要快吧,另外它接完之后放在硬盘上,我处理的时候就要再次与硬盘交互。不如接一个处理一个来的快吧。

不是,直接对流的处理来的快。不要多次 http 请求。

#6 楼 @jimrokliu 哦啊,那对流处理的话,要怎么操作啊?没有接触过...

如果过简单的文件上传,你就用 carrierwave。如果你要想自己控制流,你需要懂一些 rack, rfc 1867

#8 楼 @jimrokliu 只是上传图片,用 carrierwave 会不会太重了?

其他的组件我确实不知道,你找找看。如果不用 carrierwave,你多次拆分的图片准备用什么组件接收?弄成字符串吗?

#10 楼 @jimrokliu mini_magick 能不能接?我知道它可以接 stream, blob 的

你可以试试。mini_magick 好像不行。

上传文件,只要用 f.file_field 来提交就可以了

如果服务器的磁盘是内存盘,估计接收到了马上写入文件,而不是等接收完了再一次写入。 万一上传的文件有 1G, 难道要占用 1G 内存?

你可以使用 http://www.sinatrarb.com/intro.html

get '/post.*' do
  t = %w[text/css text/html application/javascript]
  request.accept              # ['text/html', '*/*']
  request.accept? 'text/xml'  # true
  request.preferred_type(t)   # 'text/html'
  request.body                # request body sent by the client (see below)
  request.scheme              # "http"
  request.script_name         # "/example"
  request.path_info           # "/foo"
  request.port                # 80
  request.request_method      # "GET"
  request.query_string        # ""
  request.content_length      # length of request.body
  request.media_type          # media type of request.body
  request.host                # "example.com"
  request.get?                # true (similar methods for other verbs)
  request.form_data?          # false
  request["some_param"]       # value of some_param parameter. [] is a shortcut to the params hash.
  request.referrer            # the referrer of the client or '/'
  request.user_agent          # user agent (used by :agent condition)
  request.cookies             # hash of browser cookies
  request.xhr?                # is this an ajax request?
  request.url                 # "http://example.com/example/foo"
  request.path                # "/example/foo"
  request.ip                  # client IP address
  request.secure?             # false (would be true over ssl)
  request.forwarded?          # true (if running behind a reverse proxy)
  request.env                 # raw env hash handed in by Rack
end

数据都在 request.body

自己读 socket,就能控制 buffer 了,读一点写一点就可以了 大概这样:http://stackoverflow.com/questions/13533382/how-to-read-from-a-tcpserver-socket-in-ruby-using-read-readpartial-and-read-non

先谢过各位的指导,我先研究一下~~

需要 登录 后方可回复, 如果你还没有账号请 注册新账号