[英]Ruby on rails save base64 to xlsx (or pdf or word) and save it with paperclip
我有一個像我這樣在線生成的base64
,用於xlsx
文件。 我想對其進行解碼,並使用paperclip
將其保存在db中,所以我這樣做了:
decoded_data = Base64.decode64(Base64)
data = StringIO.new(decoded_data)
data.class_eval do
attr_accessor :content_type, :original_filename
end
data.content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Model.create(file: data)
它創建一個文件並將其保存在數據庫中,但文件已損壞。 我試過它的image
與image content type
和它的罰款,但對於pdf
, word
和xlsx
它不是罰款。 你有什么線索嗎? 提前致謝。
我已經解決了這個問題。 問題是內容類型。當我嘗試通過rails_admin
存儲文件時,file_content_type為:
for xlsx file content_type = "application/zip"
for csv file content_type = "text/plain"
for pdf file content_type = "application/pdf"
for word file content_type = "application/zip"
for image file content_type = "image"
但是,當我嘗試存儲base64文件時, content_type
卻大不相同,如下所示:
for xlsx file content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
for csv file content_type = "text/plain"
for pdf file content_type = "application/pdf"
for word file content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
for image file content_type = "image/jpg"
所以我替換了正確的類型,問題解決了。
decoded_data = Base64.decode64(modified_base64)
data = StringIO.new(decoded_data)
data.class_eval do
attr_accessor :content_type, :original_filename
end
if params[:contentType] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
@content_type = "application/zip"
elsif params[:contentType] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
@content_type = "application/zip"
elsif params[:contentType] == "text/plain"
@content_type = "text/plain"
elsif params[:contentType] == "application/pdf"
@content_type = "application/pdf"
elsif params[:contentType].include?('image')
@content_type = "imgae"
end
data.content_type = @content_type
data.original_filename = params[:file_name]
並且不要忘記設置文件名,例如,如果文件是xlsx
,則可以將其命名為sample.xlsx
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.