ddavison
ddavison

Reputation: 29032

Rails POST base64 image data

I'm experiencing some interesting behavior when trying to send base64 encoded .png data to my controller.

my_controller.rb

def post_the_data
  require 'base64'

  return render :json => {
    :success => false,
    :message => 'you need to specify the data and module parameter.'
  } unless params[:data] && params[:module]

  file = "#{Rails.root}/public/pics/pics#{params[:module]}.png"

  png = Base64.decode64(params[:data])

  File.open(file, 'wb') { |f| f << png }

  if File.exist?(file)
    render :json => {
      :success => true
    }
  else
    render :json => {
      :success => false,
      :message => 'something went wrong when saving ' + file
    }
  end
end

In my shell, i am taking a 100x100px image and simply executing:

curl --data "module=HI&data=`cat ~/Pictures/yo.png | base64`" http://localhost:3000/api/pics/pics

which will take my yo.png (the url linked above) and convert it to base64

I then do a open workspace/rails4dashboard/qa-dashboard/public/pics/picsHI.png

Interesting part is, when i execute that, it opens the file, but it's Blank! The picture is 100x100, but has no pixel data inside?

What is happening! (I've already validated routing is not the issue.)

Upvotes: 0

Views: 1730

Answers (1)

William Weckl
William Weckl

Reputation: 2465

You can do that:

png = Base64.decode64(params[:data].gsub(/\n/, '').gsub(' ', '+'))

Explanation:

Base64.decode64 some times adds newlines to the string, we should remove them.

Rails replaces + with a space at params, replace it back to +.

Was with the same issue. This solved my problem.

Upvotes: 2

Related Questions