Ruby-如何使用Shrine设置data_uri(base64)文件名

时间:2018-08-15 15:16:42

标签: ruby-on-rails ruby upload base64 shrine

我正在尝试将文件名设置为使用Shrine gem和FileSystem存储上传的base64文件。

我尝试修改file.metadata[:filename] = 'test.png',但文件名仍然为空。

anex = Anex.new(file_data_uri: file) # file is a base64 string
resource.anexes << anex
resource.save!

shrine.rb

require "shrine"
require "shrine/storage/file_system"

Shrine.storages = {
  cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/cache"), # temporary
  store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/store"), # permanent
}

Shrine.plugin :activerecord
Shrine.plugin :cached_attachment_data # for forms
Shrine.plugin :data_uri # for base_64
Shrine.plugin :infer_extension
# Shrine.plugin :rack_file # for non-Rails apps

FileUploader.rb

class FileUploader < Shrine
  # plugins and uploading logic

end

Anex.rb

class Anex < ApplicationRecord
  belongs_to :anexable, polymorphic: true

  include FileUploader::Attachment.new(:file) # adds an `file` virtual attribute

  def url
    "#{ENV['FILE_STORAGE_URI']}#{self.file.url}"
  end
end

1 个答案:

答案 0 :(得分:2)

您可以在分配数据URI后通过更新file_data列来添加文件名:

anex = Anex.new(file_data_uri: data_uri)
file = anex.file
file.metadata["filename"] = "test.png"
anex.file_data = file.to_json