Question

i'm using Ruby on Rails and i want to store images into the cassandra database directly.

How can i store files with the cassandra-cql gem into the cassandra database? And how can i display this file in an image_tag?

Était-ce utile?

La solution

First make sure that your column family validator is BytesType. Then you could insert your img into Cassandra like so:

File.open('/tmp/image.jpg', 'r') do |f|
  img = f.read.force_encoding('ASCII-8BIT') # ensure cassandra-cql knows this is binary
  handle.execute("insert into img (KEY, colA) values ('rowA', ?)", img);
end

To fetch it back out:

img = handle.execute("select colA from img where KEY = 'rowA'").fetch[0]

To serve this from rails you will need to make a controller with an action to stream the img using send_data with disposition => 'inline':

class ImgController < ApplicationController
  def img
    row_key = params['row_key']
    col_name = params['col_name']
    img = handle.execute("select ? from img where KEY = ?", col_name, row_key).fetch[0]
    send_data(img, :filename => 'img.jpg', :type => 'image/jpeg', :disposition => 'inline')
  end
end

Then you can use image_tag to link to that controller. Take a look at this question for more info on streaming images from a controller.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top