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

Ruby - How to set data_uri (base64) filename with Shrine

我正在尝试将文件名设置为使用 Shrine gem 和文件系统存储上传的 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

您可以在分配数据 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