Base64 Image loaded with stringIO carrierwave media gets corrupted when loaded onto rails

This is what I do:

In the 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 carrier gem loader.

The problem is that I am not getting any errors and the image is loading, but its damage.

When I try to open it in a browser, I get this error:

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

Also note that I can recover an image from my base64_encoded data from my database. But it was not possible to save it as a jpeg image with a carrier.

0
source share
1 answer

Image Presentation:

 data:image/jpeg;base64,/9jblablablabla 

Use regexp to get data:image/jpeg and /9jblablablabla

image/jpeg will be your file type

/9jblablablabla is the image of the image.

An incorrect decoding source can damage the image file. Then you can use FileTemp to create and save the file. Hope this helps others too.

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

+2
source

All Articles