I am trying to retrieve the content-type and filename of an image which i am receiving in base64 encoded format.
here is the code which is doing a POST request with the base64 encoded image
require 'net/http'
require "rubygems"
require 'active_support'
url = URI.parse('http://localhost:3000/')
image = ActiveSupport::Base64.encode64(open("public/images/rails.png").to_a.join)
post_params = {'image' => image }
Net::HTTP.post_form(url, post_params)
In the controller, I need to get the content-type and filename of this image. So first I am decoding it
image = ActiveSupport::Base64.decode64(params[:image])
image_data = StringIO.new(image)
and then I am stuck!
I basically want to save this image using paperclip. Need some serious help!
UPDATE : I can't send params for content-type and filename. I was just mimicking the client which is sending this (and i have no control on adding extra params)
You could decode the raw bytes using one of the various ImageMagick libraries and then ask ImageMagick for the format. For example, with RMagick:
require 'rmagick'
bytes = ActiveSupport::Base64.decode64(params[:image])
img = Magick::Image.from_blob(bytes).first
fmt = img.format
That will give you 'PNG'
, 'JPEG'
, etc. in fmt
. ImageMagick checks the bytes for magic numbers and other identifying information so it doesn't need a filename to know what sort of image you're giving it.
As far as the filename goes, you're out of luck unless someone explicitly tells you what it is. The filename rarely matters anyway and you should never use a filename you didn't generate for saving anything; a user supplied filename should only be used to display the name to people, make up your own filename (that you know is safe) if you need one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With