如何使用Paperclip正确保存base64图像

时间:2015-12-21 16:46:37

标签: ruby-on-rails ruby paperclip

我正在尝试通过我的Rails应用程序中的Paperclip保存base64图像。

以下是我在控制器中的内容:

    @user = current_user
    @user.image_data = "data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAAXNSR0IArs4c6QAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAALiMAAC4jAHM9rsvAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgpMwidZAAAGAklEQVRoBe2Ya6hVRRTHr6VZkRVlb7O06E1QIRh9yMwICitCekGKHzKKiKAioggyoQckRBaFFUJ9CMowqU8pCRVBJZEZliAY2oegF70te/x+Z+//Ye7meLzee07eCy347ZlZs2bNWntmz97nDAz0R/at3R5FeVUxxT5FfdRXx9cRHk25Dv6BxRBJkmmPyjJBnkp0H4NJ/FGXz1JmRWKHanTJOMJJkDOpbwOTeAYugI11eyXlIaCMumRMQpTL4HswiaUQ/TTq79b6dZRuO2XUJJNVMKj58DeYxN0QmVBXDqZcBfZvgLNA2evJlAHcSUAGKIsgkkRjO5GO5aDddjgfFO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L8FHI+4VqS+ZxjfPSPr4s9SfWnwAlK1W1BgYupfIK/A4Zq9+mz8w1pETiyLLpzG20AmZCZBGVjEnAaceH5WvgKkR8Dt0+a6Fp30wg/cNOJA4MME7UuZV8fuaA4mqpN4AyGZ899R+Ax73iCWTy+Q2SOfRfjo2+LBPDHq9I6cS6gcZZ+h5Ep7wI6tKf8kt0x4JH52LYBBkb+90lEPv4HHEicejEudvqFoDyHtj2wbb0hPJn8lTYAurEG9JcvfR1K3ueSCaLY5OaDR6vmyH9V1L32+jTWqd9xsRmT8qM7dmKlJPH+TcEeSL4EfoL3AvKatDeZIe6hUr/ZT1ztRPJuwDfIxbfBU7gl4J/HsyC02A7PAVzwW2kXfPYRTUyKY/BkXmqRntjTMb3zMuwDe6AW8E76nw9TwKfHT8n1I9ETMagfVY8bt1iShKpWj2+ZtIeu23ddQOfUTvuaxLO0belxrdbKA91X7aTCURckX5Kr5/BZqyudEv6PVHm6VfZXumxnsj/K9KvLTJcv4NWpN0Yrre9OG7QM9Ju7MWAhjt1exHG+sPeXoSxnkh7RfKJ4htYsWxn2dKMzotx+hU9KBFXZVIdr/9pjQXJTmr/geiK+ONnGRwP/u80VlbEJNZAS/4FZ2ox94giRB8AAAAASUVORK5CYII="

    @user.save!

    StringIO.open(Base64.decode64(@user.image_data)) do |data|
      data.class.class_eval { attr_accessor :original_filename, :content_type }
      data.original_filename = "file.jpg"
      data.content_type = "image/jpeg"
      @user.image = data
    end

    @user.save! 

以下是我在用户模型中的内容:

has_attached_file :image, styles: {
    square: '300x300>'
  }

  validates_attachment :image, content_type: { content_type: ["image/jpeg", "image/jpg"] }, size: { in: 0..10.megabytes }

我一直收到此错误:Validation failed: Image content type is invalid, Image is invalid

我如何让它工作?如何正确保存base64图像?

1 个答案:

答案 0 :(得分:0)

您需要只对64位编码为base 64的部分进行解码。

"data:image/jpg;base64,iVBORw0KGgo..."中,以iVB...开头的部分是base 64编码图像。

i = @user.image_data
image_data = i[i.index("base64,") + "base64,".size, i.size]
#=> iVBOR....
image = Base64.decode64(image_data)

StringIO.open(image) do |data|
  ...
end
...