Ruby on rails 如何显示从Mongoid::GridFs返回的图像
我正试图用rails_admin gem在记录行中显示保存在Mongo中的图像 我保存了模型和图像,并将图像ID保存在模型记录中 这是我的模型:Ruby on rails 如何显示从Mongoid::GridFs返回的图像,ruby-on-rails,mongoid,gridfs,rails-admin,Ruby On Rails,Mongoid,Gridfs,Rails Admin,我正试图用rails_admin gem在记录行中显示保存在Mongo中的图像 我保存了模型和图像,并将图像ID保存在模型记录中 这是我的模型: require 'mongoid/grid_fs' class Asset include Mongoid::Document field :data_file_name, type: String field :data_content_type, type: String field :data_file_size, t
require 'mongoid/grid_fs'
class Asset
include Mongoid::Document
field :data_file_name, type: String
field :data_content_type, type: String
field :data_file_size, type: Integer
field :image_id, type: String
end
以下是我在rails_admin.rb中为我的资产模型所做的工作:
list do
field :id
field :data_file_name
field :data_content_type
field :data_file_size
field :image do
formatted_value do
grid_fs = Mongoid::GridFs
bindings[:view].tag(:img, { :src => grid_fs.get(bindings[:object].image_id)})
end
end
end
以下是负责保存模型和图像的操作:
register_instance_option :controller do
proc do
if request.get? # EDIT
respond_to do |format|
format.html { render @action.template_name }
format.js { render @action.template_name, layout: false }
end
elsif request.put? # UPDATE
tempFile = params[:picture][:asset].tempfile
file = File.open(tempFile)
grid_fs = Mongoid::GridFS
grid_file = grid_fs.put(file.path)
Asset.new.tap do |asset|
asset.data_file_name = params[:picture][:asset].original_filename
asset.data_content_type = params[:picture][:asset].content_type
asset.data_file_size = ::ApplicationController.helpers.number_to_human_size(File.size(tempFile))
asset.image_id = grid_file.id
asset.save
binding.pry
end
end
end
end
模型正在保存,我可以看到文件保存在fs.files和fs.chunks中,但目前,我只在记录行中看到以下内容:
更新:
我现在尝试从mongo获取文件(这似乎可行),然后使用文件的实际文件名显示图像
field :image do
formatted_value do
grid_fs = Mongoid::GridFs
f = grid_fs.get(bindings[:object].image_id)
bindings[:view].tag(:img, { :src => f.filename})
end
end
不幸的是,这并没有改变任何事情。尝试在新选项卡中打开图像时,我会看到以下链接:/admin/asset
更新2:
将字段:image\u id,类型:String
更改为字段:image\u id,类型:BSON::ObjectId
结果没有变化。如果要在GridFS中保存图像数据,则需要在应用程序中有一个端点,以便从GridFS中检索图像数据并将其提供给应用程序。有关如何提供图像数据,请参见此答案:
然后,链接到此端点,而不是像您在上一个代码片段中所指出的那样链接到“f.filename”。经过更多的研究,看起来您可以将从
grid\u fs
返回的数据编码到base64
反过来,您可以通过将源指定为data:image/png;base64,+base64图像
类似于:
field :asset_thumbnail do
formatted_value do
grid_fs = Mongoid::GridFs
f = grid_fs.get(bindings[:object].thumb_image_id)
b64 = Base64.strict_encode64(f.data)
bindings[:view].tag(:img, { :src => "data:image/png;base64,"+b64})
end
end
感谢您抽出时间回答。我只是想知道,如果不在本地保存文件,是否就无法显示图像?理想情况下,我只需使用以下命令从GridFs提取图像数据:
f=grid\u fs.get(bindings[:object].image\u id)file=file.new(bindings[:object].data\u file_name,'wb')f.each{chunk | file.write(chunk)}
然后以某种方式显示文件。您不需要将数据从GridFs复制到本地文件系统来提供服务,但您仍然需要一个端点来从GridFS检索数据,然后将其转发到浏览器。