使用stringIO carrierwave gem上传的base64图像在rails中上传时损坏 [英] base64 Image uploaded with stringIO carrierwave gem gets corrupt on upload in rails

查看:78
本文介绍了使用stringIO carrierwave gem上传的base64图像在rails中上传时损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在做什么:

在控制器中:-

    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    

型号:-

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是一个简单的载波宝石上传器

BaseSixtyfourEncodedUploader is a simple uploader of 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.

另外请注意,我能够从数据库的base64_encoded数据中重新生成图像。但是无法使用载波将其保存为jpeg图像。

Also please note that I'm able to regenerate the image from my base64_encoded data from my database. But not able to save it as a jpeg image with carrierwave.

推荐答案

图像表示形式为:

data:image/jpeg;base64,/9jblablablabla

使用 regexp 获得值
data:image / jpeg / 9jblablablabla

image / jpeg 将是您的文件类型

/ 9jblablablabla 将是图像的表示

解码错误的源可能会导致图像文件损坏。
然后,您可以使用FileTemp创建和保存文件。希望它也能帮助其他人..

Decoding wrong source might cause the image file corrupted. Then, you can use FileTemp to create and save the file. Hope its help others too ..

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

这篇关于使用stringIO carrierwave gem上传的base64图像在rails中上传时损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆