The*_*pro 5 excel blob ruby-on-rails rails-activestorage ruby-on-rails-5.2
我有这门课,我正在使用活动存储
class DataSheet < ApplicationRecord
belongs_to :admin
has_one_attached :excel_file
after_save :create_user
end
Run Code Online (Sandbox Code Playgroud)
我知道有很多 gems creek、write_xlsx_rails、roo可以读取或写入 .xlsx 文件,但它们都需要文件的物理位置。以前,我使用creek gem读取 .xlsx 文件,但我必须将该文件保存在本地。
class LocalFileUploader
attr_reader :file
def initialize(file = nil)
@file = file
end
def save
file_path = Rails.root.join('storage', file.original_filename)
IO.copy_stream(file.path, file_path)
return file_path.to_s
end
end
Run Code Online (Sandbox Code Playgroud)
现在我正在使用将 .xlsx 文件存储为二进制文件的主动存储。我无法找到将该文件作为 xlsx 文件读取的方法。虽然主动存储提供了下载方法来获取文件的二进制数据。
pry(#<DataSheet>)> self.excel_file
=> #<ActiveStorage::Attached::One:0x007f9db0607750
@dependent=:purge_later,
@name="excel_file",
@record=#<DataSheet:0x007f9db811ba40 id: 3, admin_id: 1, created_at: Mon, 28 May 2018 01:33:06 UTC +00:00, updated_at: Mon, 28 May 2018 01:33:06 UTC +00:00>>
[3] pry(#<DataSheet>)> self.excel_file.blob
=> #<ActiveStorage::Blob:0x007f9db81125f8
id: 6,
key: "TBitz1dEzma2R2uTgtEoJ7X1",
filename: "faizabad 1424.xlsx",
content_type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
metadata: {"identified"=>true},
byte_size: 374211,
checksum: "/shAXf0kEnYV4DGl0z3fng==",
created_at: Mon, 28 May 2018 01:33:06 UTC +00:00>
[4] pry(#<DataSheet>)> SimpleXlsxReader.open self.excel_file.blob
TypeError: no implicit conversion of ActiveStorage::Blob into String
from /home/rotlu_crush/.rvm/gems/ruby-2.4.1/gems/rubyzip-1.2.1/lib/zip/file.rb:73:in `size?'
[5] pry(#<DataSheet>)> SimpleXlsxReader.open self.excel_file.blob.download
Disk Storage (0.6ms) Downloaded file from key: TBitz1dEzma2R2uTgtEoJ7X1
ArgumentError: string contains null byte
from /home/rotlu_crush/.rvm/gems/ruby-2.4.1/gems/rubyzip-1.2.1/lib/zip/file.rb:73:in `size?'
Run Code Online (Sandbox Code Playgroud)
我在某处阅读了一个示例,通过将二进制数据解析为 csv 来读取具有活动存储的csv 文件数据。
CSV.parse(materials_upload.csv_file.download, headers: true) do |row|
# ...
end
Run Code Online (Sandbox Code Playgroud)
有没有办法读取带有活动存储的excel文件?
Rails 6 将添加ActiveStorage::Blob#open,它将 blob 下载到临时文件中:
data_sheet.excel_file.open do |file|
# Operate on the file
end
Run Code Online (Sandbox Code Playgroud)
您现在可以从 GitHub 捆绑 Rails 来使用此功能:
gem "rails", github: "rails/rails"
Run Code Online (Sandbox Code Playgroud)