检测 Ruby 中上传文件的 MIME 类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4600679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect MIME type of uploaded file in Ruby
提问by Vincent
Is there a bullet proof way to detect MIME type of uploaded file in Ruby or Ruby on Rails? I'm uploading JPEGs and PNGs using SWFupload and content_typeis always "application/octet-stream"
是否有防弹方法来检测 Ruby 或 Ruby on Rails 中上传文件的 MIME 类型?我正在使用 SWFupload 上传 JPEG 和 PNG,content_type并且总是"application/octet-stream"
回答by Wayne Conrad
The ruby-filemagicgem will do it:
该红宝石filemagic创业板将做到这一点:
require 'filemagic'
puts FileMagic.new(FileMagic::MAGIC_MIME).file(__FILE__)
# => text/x-ruby; charset=us-ascii
This gem does not look at the file extension at all. It reads a bit of the file contents and uses that to guess the file's type.
这个 gem 根本不看文件扩展名。它读取一些文件内容并使用它来猜测文件的类型。
回答by NARKOZ
In Ruby on Rails you can do:
在 Ruby on Rails 中,您可以执行以下操作:
MIME::Types.type_for("filename.gif").first.content_type # => "image/gif"
回答by Alain Beauvois
You can use this reliable method base on the magic header of the file :
您可以根据文件的魔术头使用这种可靠的方法:
def get_image_extension(local_file_path)
png = Regexp.new("\x89PNG".force_encoding("binary"))
jpg = Regexp.new("\xff\xd8\xff\xe0\x00\x10JFIF".force_encoding("binary"))
jpg2 = Regexp.new("\xff\xd8\xff\xe1(.*){2}Exif".force_encoding("binary"))
case IO.read(local_file_path, 10)
when /^GIF8/
'gif'
when /^#{png}/
'png'
when /^#{jpg}/
'jpg'
when /^#{jpg2}/
'jpg'
else
mime_type = `file #{local_file_path} --mime-type`.gsub("\n", '') # Works on linux and mac
raise UnprocessableEntity, "unknown file type" if !mime_type
mime_type.split(':')[1].split('/')[1].gsub('x-', '').gsub(/jpeg/, 'jpg').gsub(/text/, 'txt').gsub(/x-/, '')
end
end
回答by Marc
The ruby-filemagic gem is good solution, but requires additional dependencies on libmagic(recently removed from CarrierWave as part of CarrierWave::MagicMimeTypesremoval).
ruby-filemagic gem 是一个很好的解决方案,但需要额外依赖libmagic(最近作为CarrierWave::MagicMimeTypes删除的一部分从 CarrierWave 中删除)。
If you're interested in a pure ruby implementation, consider the MimeMagicgem! It works well for file types listed in the freedesktop.org mime database:
如果您对纯 ruby 实现感兴趣,请考虑MimeMagicgem!它适用于 freedesktop.org mime 数据库中列出的文件类型:
require 'mimemagic'
MimeMagic.by_magic(File.open('Table-Flip-Guy.jpg')).type # => "image/jpeg"
For Microsoft Office 2007+ formats (xlsx, docx, and pptx), require the overlay (unless you're okay with the generic "application/zip" MIME type for these files)
对于 Microsoft Office 2007+ 格式(xlsx、docx 和 pptx),需要覆盖(除非您同意这些文件的通用“应用程序/zip”MIME 类型)
require 'mimemagic'
require 'mimemagic/overlay'
MimeMagic.by_magic(File.open('big_spreadsheet.xlsx')).type # => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
回答by kaorukobo
filemagic gem is good solution but depends lots of unnecessary gems. (rails, aws-sdk-core, ...)
filemagic gem 是很好的解决方案,但依赖于许多不必要的 gem。(rails, aws-sdk-core, ...)
If your app is small and only runs in Linux or OSX, consider to use fileprogram:
如果您的应用程序很小并且仅在 Linux 或 OSX 中运行,请考虑使用file程序:
require 'shellwords'
mimetype = `file --brief --mime-type - < #{Shellwords.shellescape(__FILE__)}`.strip
Note: Replace __FILE__with any expr contains the filepath.
注意:替换__FILE__为任何包含文件路径的 expr。
回答by priki
mimemagic gem will also do it
mimemagic gem 也会这样做
https://github.com/minad/mimemagic
https://github.com/minad/mimemagic
from the oficial documentation
来自官方文档
MimeMagic is a library to detect the mime type of a file by extension or by content. It uses the mime database provided by freedesktop.org (see http://freedesktop.org/wiki/Software/shared-mime-info/).
require 'mimemagic' MimeMagic.by_extension('html').text? MimeMagic.by_extension('.html').child_of? 'text/plain' MimeMagic.by_path('filename.txt') MimeMagic.by_magic(File.open('test.html')) # etc...
MimeMagic 是一个通过扩展名或内容来检测文件的 MIME 类型的库。它使用 freedesktop.org 提供的 mime 数据库(参见http://freedesktop.org/wiki/Software/shared-mime-info/)。
require 'mimemagic' MimeMagic.by_extension('html').text? MimeMagic.by_extension('.html').child_of? 'text/plain' MimeMagic.by_path('filename.txt') MimeMagic.by_magic(File.open('test.html')) # etc...
回答by Siva
You can use
您可以使用
Mime::Type.lookup_by_extension(extention_name)
Mime::Type.lookup_by_extension(extention_name)
Thanks
谢谢

