Extract file name and content type from base64 encoded image on rails

I am trying to get the content type and image file name that I get in base64 encoded format.

here is the code that executes the POST request with a 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 file name of this image. So first I decode it

 image = ActiveSupport::Base64.decode64(params[:image]) image_data = StringIO.new(image) 

and then I'm stuck!

Basically I want to save this image using paperclip. I need some serious help!

UPDATE: I cannot send parameters for content type and file name. I just imitated the client who sends it (and I have no control over adding additional parameters)

+6
source share
2 answers

You can decode raw bytes using one of the various ImageMagick libraries, and then ask ImageMagick for the format. For example, RMagick :

 require 'rmagick' bytes = ActiveSupport::Base64.decode64(params[:image]) img = Magick::Image.from_blob(bytes).first fmt = img.format 

This will give you 'PNG' , 'JPEG' , etc. in fmt . ImageMagick checks bytes for magic numbers and other identifying information, so it does not need a file name to find out which image you give it.

As for the file name, you're out of luck if someone clearly doesn't tell you what it is. A file name rarely matters, and you should never use a file name that you did not create to save anything; the user-provided file name should only be used to display the name for people, for your own file name (which you know is safe) if you need it.

+4
source

For the file name, why don't you just post it, it seems easier ( post_params = {'image' => image, 'file_name' => same_file_you_passed_to_encode64 } ). You can use a ruby-filemagic type library to find the content type.

http://rubygems.org/gems/ruby-filemagic

0
source

Source: https://habr.com/ru/post/894377/


All Articles