Rails: how to get a file extension/postfix based on the mime type
Rack::Mime
has this ability (and Rack is a dependency of Rails):
require 'rack/mime'
Rack::Mime::MIME_TYPES.invert['image/jpeg'] #=> ".jpg"
You may wish to memoize the inverted hash if you’re going to do the lookup often, as it’s not an inexpensive operation.
How to get the default extension for a given content type?
Your second solution with the mime type is the solution, which you should choose. There are several reasons for that:
- The second solution is exactly designed for your use case
Hack the string
could be inconsistent or return unexpected results (think aboutapplication/postscript
has the extensioneps
!)- Please consider, that we probably can't say, that every mime type has it's default extension. For example: who has defined the default extension for jpg (or jpeg or JPG..) images?
how to get mime type of a file,which has dot in the file name on android
How about this:
File f = new File(file);
System.out.println(new MimetypesFileTypeMap().getContentType(f));
Or
if(url.lastIndexOf(".") != -1) {
String ext = url.substring(url.lastIndexOf(".")+1);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getMimeTypeFromExtension(ext);
} else {
String type = null;
}
Convert mimetype to file extension
include <MobileCoreServices/MobileCoreServices.h>
or <CoreServices/CoreServices.h>
then just following code:
CFStringRef mimeType = (CFStringRef)@"audio/x-aiff";
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL);
CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);
Ruby: Get filename without the extensions
Thanks to @xdazz and @Monk_Code for their ideas. In case others are looking, the final code I'm using is:
File.basename(__FILE__, ".*").split('.')[0]
This generically allows you to remove the full path in the front and the extensions in the back of the file, giving only the name of the file without any dots or slashes.
Related Topics
How to Organize Minitest/Unit Tests
How to Install 'Cocoapods' Gem from Rubygems.Org (Bad Response Backend Read Error)
What Does the Underscore Mean in Literal Numbers
Spork 0.9.2 and Rspec 3.0.0 = Uninitialized Constant Rspec::Core::Commandline (Nameerror)
How to Update Gems in Ruby for Windows
Get Server File Path with Paperclip
Changing Active Model Serializers Default Adapter
Finding Lines in a Text File Matching a Regular Expression
Sinatra with a Persistent Variable
What's the Difference Between Bundle.Setup and Bundle.Require
Ruby: How to Group a Ruby Array
Rake Assets:Precompile Gets Killed When There Is a Console Session Open in Production
How to Use Ruby " Case ... When " with Inequalities
Can't Convert Symbol into String
Testing After_Commit with Rspec and Mocking