I have a base64
like this which I have generated on-line.It's for an xlsx
file. I want to decode it and save it in db with paperclip
so I did this :
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)
it creates a file and saves it on database but the file is damaged. I've tried it for image
with image content type
and it's fine but for pdf
,word
and xlsx
it's not fine . Do you have any clue ?
Thanks in advance.
I've fixed the issue. The problem was for the content type.When I tried to store the files through rails_admin
the file_content_type was :
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"
But when I was trying to store the base64 file the content_type
was quite different as you see below:
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"
So I replaced that correct type and the problem soveld.
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]
And don't forget to set the file name, for example if the file is xlsx
you can name it as sample.xlsx
that's a big deal.