简体   繁体   English

使用回形针上传base64编码的图像-Rails

[英]Upload base64 encoded image with paperclip - Rails

Using cropit I get the image bas64 encode on rails through params. 使用cropit,我通过参数将图像bas64编码在轨道上。

  image = params['image'].gsub('data:image/jpeg;base64,', '')
  decoded_file = Base64.decode64(image)

and then I save to amazon s3 with paperclip 然后我用回形针保存到Amazon s3

   begin
    file = Tempfile.new(['image', '.jpg'])
    file.binmode
    file.write decoded_file
    unless params['image_id']
      media_img = Media::Image.new()
      media_img.image = file
      if media_img.save
        render json: {status: 'success'}
      else
        render json: {status: 'error'}
      end
    else
      img = Media::Image.find(params['image_id'])
      img.update_attribute(:image, file)
      img.update_attribute(:name, params['image_name'])
      render json: {status: 'success'}
    end
    file.close
  ensure
    file.unlink
  end

The main problem is that the code is working only for jpeg images because I use gsub only for data:image/jpeg;base64, and when creating the Tempfile I created jpg Tempfile.new(['image', '.jpg']) . 主要问题是该代码仅适用于jpeg图像,因为我仅将gsub用于data:image/jpeg;base64,并且在创建Tempfile时创建了jpg Tempfile.new(['image', '.jpg']) So how can I handle with best practice jpg, jpeg and png? 那么,如何使用jpg,jpeg和png最佳实践进行处理?

This is my solution, using Paperclip.io_adapters.for(image) where image is base64 string. 这是我的解决方案,使用Paperclip.io_adapters.for(image),其中image是base64字符串。

def create_image image, image_name, cat
  signature = Paperclip.io_adapters.for(image)
  base_name = File.basename(image_name,File.extname(image_name))
  signature.original_filename = "#{base_name}.jpg"
  media_img = Media::Image.new()
  media_img.image = signature
  media_img.company_id = current_company_id
  media_img.type = cat
  media_img.save
end

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

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