从 base64 编码图像 ruby​​ on rails 检索文件名和内容类型 [英] retrieve filename and content-type from base64 encoded image ruby on rails

查看:49
本文介绍了从 base64 编码图像 ruby​​ on rails 检索文件名和内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索以 base64 编码格式接收的图像的内容类型和文件名.

I am trying to retrieve the content-type and filename of an image which i am receiving in base64 encoded format.

这是使用 base64 编码图像执行 POST 请求的代码

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)

然后我就卡住了!

我基本上想用回形针保存这张图片.需要一些认真的帮助!

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)

推荐答案

您可以使用各种 ImageMagick 库之一解码原始字节,然后向 ImageMagick 询问格式.例如,使用 RMagick:

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

这将在 fmt 中为您提供 'PNG''JPEG' 等.ImageMagick 会检查字节中的幻数和其他识别信息,因此它不需要文件名就可以知道您提供的是哪种类型的图像.

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.

这篇关于从 base64 编码图像 ruby​​ on rails 检索文件名和内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆