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

时间:2018-02-27 18:37:55

标签: ruby-on-rails ruby base64 paperclip xlsx

我有一个base64这样我在online上生成的。它是xlsx文件。我想解码它并将其保存在db paperclip中,所以我这样做了:

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来说并不好。你有什么线索吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。问题出在内容类型上。当我尝试通过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" 存储文件时,file_content_type为:

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]

但是当我试图存储base64文件时,xlsx完全不同,如下所示:

sample.xlsx

所以我更换了正确的类型和问题soveld。

.wrapper {
  display: flex;
  align-items: center; /* vertical center */
  justify-content: center; /* horizontal center */
  border: 1px solid red;
}

button {
  height: 50px;
}

.wrapper>div {
  display: inline-block;
  height: 70px;
  border: 2px solid black;
  padding: 10px;
}

h1 {
  display: inline-block;
}

并且不要忘记设置文件名,例如,如果文件是<div class="wrapper"> <div></div> <button>Button</button> <span>Span</span> <div>div</div> </div>,您可以将其命名为{{1}},这是一个大问题。