我正在使用 Ruby on Rails,我想将图像直接存储到 cassandra 数据库中。
如何将带有 cassandra-cql gem 的文件存储到 cassandra 数据库中?我怎样才能在 image_tag 中显示这个文件?
我正在使用 Ruby on Rails,我想将图像直接存储到 cassandra 数据库中。
如何将带有 cassandra-cql gem 的文件存储到 cassandra 数据库中?我怎样才能在 image_tag 中显示这个文件?
首先确保您的列族验证器是 BytesType。然后你可以像这样将你的 img 插入 Cassandra:
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
要取回它:
img = handle.execute("select colA from img where KEY = 'rowA'").fetch[0]
要从 rails 提供此服务,您需要使用以下操作制作一个控制器以流式传输send_data
img 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
然后您可以使用 image_tag 链接到该控制器。查看这个问题以获取有关来自控制器的流式图像的更多信息。