简体   繁体   English

base64使用stringIO上传的图片carrierwave gem在rails上传时会损坏

[英]base64 Image uploaded with stringIO carrierwave gem gets corrupt on upload in rails

This is what I'm doing: 这就是我正在做的事情:

In controller:- 在控制器中: -

    dataurl = params[:dataURL]
    io = FilelessIO.new(Base64.decode64(dataurl))
    io.original_filename = "foobar.jpeg"
    io.content_type = "image/jpeg"
    p = SketchilyTest.new
    p.image = io
    p.save    

Model:- 模型:-

class FilelessIO < StringIO
    attr_accessor :original_filename
    attr_accessor :content_type
end
class SketchilyTest < ActiveRecord::Base
  attr_accessible :desc, :image
  mount_uploader :image, BaseSixtyfourEncodedUploader

end

BaseSixtyfourEncodedUploader is a simple uploader of carrierwave gem BaseSixtyfourEncodedUploader是carrierwave gem的简单上传器

The issue is that I'm not getting any errors and image gets uploaded but its corrupt. 问题是我没有收到任何错误,图片上传但是它已经损坏了。

When I'm trying to open it in the browser I'm getting this error: 当我试图在浏览器中打开它时,我收到此错误:

The image “http://localhost:3000/uploads/sketchily_test/image/41/foobar.jpeg” cannot be displayed because it contains errors.

Also please note that I'm able to regenerate the image from my base64_encoded data from my database. 另请注意,我可以从我的数据库中的base64_encoded数据重新生成图像。 But not able to save it as a jpeg image with carrierwave. 但无法将其保存为带载波的jpeg图像。

The image representation is: 图像表示为:

data:image/jpeg;base64,/9jblablablabla

Use regexp to get the value data:image/jpeg and /9jblablablabla 使用regexp获取值data:image/jpeg/9jblablablabla

image/jpeg will be your file type image/jpeg将是您的文件类型

/9jblablablabla will be the representation of the image. /9jblablablabla将是图像的表示

Decoding wrong source might cause the image file corrupted. 解码错误的源可能会导致图像文件损坏。 Then, you can use FileTemp to create and save the file. 然后,您可以使用FileTemp来创建和保存文件。 Hope its help others too .. 希望它也帮助别人..

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tempfile/rdoc/Tempfile.html http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tempfile/rdoc/Tempfile.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM