class MyLog < ApplicationRecord
has_one_attached :xlsx_file
end
我創建 .xlsx 檔案作為電子郵件附件:
xlsx = render_to_string layout: false, template: "dir/template"
xlsx_base64 = Base64.encode64(xlsx)
attachment = {mime_type: Mime[:xlsx], content: xlsx_base64, encoding: 'base64'}
attachments["file.xlsx"] = attachment
我還想將此檔案作為附件添加到 MyLog 表中:
MyLog.create(
xlsx_file: xlsx
)
但是 xlsx 是一個字串,它不起作用。在通常的示例中,可附加檔案來自帶有 ActionDispatch::Http::UploadedFile 類的 file_field 標記,并且它正在作業。如何將我新創建的 calsx .xlsx 檔案附加到我的記錄中?
uj5u.com熱心網友回復:
在不使用上傳檔案的情況下完成此操作的一種方法是.attach函式 ( docs )。
例子:
xlsx = render_to_string layout: false, template: "dir/template"
log = MyLog.create
log.xlsx_file.attach(io: StringIO.new(xlsx), filename: 'file.xlsx', content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
如果您正在從檔案系統讀取,您也可以替換StringIO.new(string_content)為。File.open(filename)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452372.html
標籤:轨道上的红宝石 rails-activestorage caxlsx
上一篇:從rails5遷移到rails6
