开发者

retrieve filename and content-type from base64 encoded image ruby on rails

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-ty开发者_C百科pe 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.


For the filename, why don't you just post that too, seems easier (post_params = {'image' => image, 'file_name' => same_file_you_passed_to_encode64 }). For finding the content-type you could use a library like ruby-filemagic.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜