Ruby on rails将base64保存为xlsx(或pdf或word)并使用paperclip保存

问题描述 投票:0回答:1

我有一个这样的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)

它创建一个文件并将其保存在数据库中,但文件已损坏。我用imageimage content type尝试了它,它很好但是对于pdfwordxlsx它并不好。你有什么线索吗?提前致谢。

ruby-on-rails ruby base64 paperclip xlsx
1个回答
0
投票

我已经解决了这个问题。问题出在内容类型上。当我尝试通过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,这是一个大问题。

© www.soinside.com 2019 - 2024. All rights reserved.