Search code examples
ruby-on-railsrubyuploadbase64shrine

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


I'm trying to set the filename to a base64 file uploaded with the Shrine gem with FileSystem store.

I tried modifying the file.metadata[:filename] = 'test.png', but the filename still nil.

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

Solution

  • You can add the filename by updating the file_data column after assigning the data URI:

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