Rails: How to Get a File Extension/Postfix Based on the Mime Type

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 about application/postscript has the extension eps!)
  • 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



Leave a reply



Submit