Guess content type based on file extension

 @param [String] ext File extension including dots

 @example Return mime type for extension '.png'
   guess_mime('favicon.png')

 @return [String] content-type value
168254
def guess_mime(ext)
      content_types = WEBrick::HTTPUtils::DefaultMimeTypes
      common_content_types = { 'ico' => 'image/x-icon' }
      content_types.merge!(common_content_types)
      content_types.each do |k, v|
        return v.to_s if ext.eql?(".#{k}")
      end
      nil
    end
77357
def guess_filetype(filepath):
    """"""
    # If we have python-magic, use it to determine file type
    typ = None

    # Some specific checks for known file suffixes
    _fn = filepath.lower()
    _name, _ext = os.path.splitext(_fn)
    if _ext in known_types:
        typ = known_types[_ext]

    if typ is None and have_magic:
        try:
            # it seems there are conflicting versions of a 'magic'
            # module for python floating around...*sigh*
            if hasattr(magic, 'from_file'):
                typ = magic.from_file(filepath, mime=True)

            elif magic_tester is not None:
                descrip = magic_tester.file(filepath)
                if descrip.startswith("FITS image data"):
                    return ('image', 'fits')

        except Exception as e:
            pass

    if typ is None:
        # if no magic, or magic fails, fall back to mimetypes
        try:
            typ, enc = mimetypes.guess_type(filepath)

        except Exception as e:
            # fail
            pass

    if typ:
        typ, subtyp = typ.split('/')
        return (typ, subtyp)

    raise ValueError("Can't determine file type of '%s'" % (filepath))
917221
def guess_content_type_and_encoding(path):
    
    for ext, content_type in _EXTENSION_TO_MIME_TYPE.items():
        if path.endswith(ext):
            return content_type

    content_type, encoding = mimetypes.guess_type(path)
    content_type = content_type or "application/binary"
    return content_type, encoding
371404
function mimeType( path ) {
	var extension = path.replace( /.*[./\\]/ , '' ).toLowerCase() ;

	if ( ! mimeType.extension[ extension ] ) {
		// default MIME type, when nothing is found
		return 'application/octet-stream' ;
	}

	return mimeType.extension[ extension ] ;
}
725197
def guess_extension(amimetype, normalize=False):
    
    ext = _mimes.guess_extension(amimetype)
    if ext and normalize:
        # Normalize some common magic mis-interpreation
        ext = {'.asc': '.txt', '.obj': '.bin'}.get(ext, ext)
        from invenio.legacy.bibdocfile.api_normalizer import normalize_format
        return normalize_format(ext)
    return ext
143397
def load_fn_matches_ext(file_path, file_type):
    
    correct_ext = False
    curr_ext = os.path.splitext(file_path)[1]
    exts = [curr_ext, file_type]
    try:
        # special case: if file type is excel, both extensions are valid.
        if ".xlsx" in exts and ".xls" in exts:
            correct_ext = True
        elif curr_ext == file_type:
            correct_ext = True
        else:
            print("Use '{}' to load this file: {}".format(FILE_TYPE_MAP[curr_ext]["load_fn"],
                                                          os.path.basename(file_path)))
    except Exception as e:
        logger_misc.debug("load_fn_matches_ext: {}".format(e))

    return correct_ext
204673
function get_type($ext)
    {
        $ext = strtolower($ext);
        // get position of last dot
        $dot_pos = strrpos($ext, '.');
        if ($dot_pos !== false) $ext = substr($ext, $dot_pos+1);
        if (($ext != '') && isset($this->mime_types[$ext])) return $this->mime_types[$ext];
        return false;
    }
387295
def guess_type_tag(self, input_bytes, filename):
        
        mime_to_type = {'application/jar': 'jar',
                        'application/java-archive': 'jar',
                        'application/octet-stream': 'data',
                        'application/pdf': 'pdf',
                        'application/vnd.ms-cab-compressed': 'cab',
                        'application/vnd.ms-fontobject': 'ms_font',
                        'application/vnd.tcpdump.pcap': 'pcap',
                        'application/x-dosexec': 'exe',
                        'application/x-empty': 'empty',
                        'application/x-shockwave-flash': 'swf',
                        'application/xml': 'xml',
                        'application/zip': 'zip',
                        'image/gif': 'gif',
                        'text/html': 'html',
                        'image/jpeg': 'jpg',
                        'image/png': 'png',
                        'image/x-icon': 'icon',
                        'text/plain': 'txt'
                        }

        # See what filemagic can determine
        with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as mag:
            mime_type = mag.id_buffer(input_bytes[:1024])
            if mime_type in mime_to_type:
                type_tag = mime_to_type[mime_type]

                # If we get 'data' back look at the filename
                if type_tag == 'data':
                    print 'Info: File -- Trying to Determine Type from filename...'
                    ext = os.path.splitext(filename)[1][1:]
                    if ext in ['mem','vmem']:
                        type_tag = 'mem'
                    else:
                        print 'Alert: Failed to Determine Type for %s' % filename
                        exit(1) # Temp
                return type_tag
            else:
                print 'Alert: Sample Type could not be Determined'
                return 'unknown'
816383
public static String fileExtensionForMIMEType(String mimeType) {
        loadMappings();

        String ext = mimeTypeToExtensionMap.get(mimeType);

        if (ext == null) ext = "dat";

        return ext;
    }
1162254
static function guessFileTypeFromMimeType($mt, $def = '')
	{
		// for audio, image, videos, this is simple, the Mime type is explicit
		if ( strpos($mt, 'audio/') === 0 )
			return 'audio';
		if ( strpos($mt, 'image/') === 0 )
			return 'image';
		if ( strpos($mt, 'video/') === 0 )
			return 'video';
		
			
		switch ( $mt )
		{
			case 'application/pdf':
				return 'pdf';
			case 'text/html':
				return 'html';
			case 'text/plain':
				return 'text';
			case 'message/rfc822':
				return 'email';
			case 'application/msword':
			case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
			case 'application/vnd.oasis.opendocument.text':
				return 'word';
			case 'application/vnd.ms-excel':
			case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
			case 'application/vnd.oasis.opendocument.spreadsheet':
				return 'excel';
			case 'application/vnd.ms-powerpoint':
			case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
			case 'application/vnd.oasis.opendocument.presentation':
				return 'powerpoint';
			case 'application/zip':
				return 'zip';
			default :
				return $def;
		}
	}
1264883
def _detect_content_type(self, filename):
        '''
        '''
        name, ext = os.path.splitext(filename)
        if not ext:
            raise MessageError('File requires an extension.')
        ext = ext.lower()
        if ext.lstrip('.') in self._banned_extensions:
            err = 'Extension "{0}" is not allowed.'
            raise MessageError(err.format(ext))
        if not mimetypes.inited:
            mimetypes.init()
        return mimetypes.types_map.get(ext, self._default_content_type)
902836
def guess_fileformat(aUri):
    
    if aUri.endswith(".xml"):
        return "xml"
    elif aUri.endswith(".nt"):
        return "nt"
    elif aUri.endswith(".n3") or aUri.endswith(".ttl"):
        return "n3"
    elif aUri.endswith(".trix"):
        return "trix"
    elif aUri.endswith(".rdfa"):
        return "rdfa"
    else:  # to be handled outside this method
        return None
798230
def mimetype(path)
      extension = File.basename(path).split('.')[-1]
      Rack::Mime.mime_type(".#{extension}")
    end
496419
def get_content_type(self) -> str:
        
        assert self.absolute_path is not None
        mime_type, encoding = mimetypes.guess_type(self.absolute_path)
        # per RFC 6713, use the appropriate type for a gzip compressed file
        if encoding == "gzip":
            return "application/gzip"
        # As of 2015-07-21 there is no bzip2 encoding defined at
        # http://www.iana.org/assignments/media-types/media-types.xhtml
        # So for that (and any other encoding), use octet-stream.
        elif encoding is not None:
            return "application/octet-stream"
        elif mime_type is not None:
            return mime_type
        # if mime_type not detected, use application/octet-stream
        else:
            return "application/octet-stream"
1194144
public static String getMediaType(String ext) {
        String mediaType = "";

        // Find the media type value in the lookup table
        for (int i = 0; i < ApplicationMediaTypeMappings.length; i++) {
            if (ApplicationMediaTypeMappings[i][0].equals(ext.toLowerCase())) {
                mediaType = ApplicationMediaTypeMappings[i][1];
            }
        }

        // Give the media type default of "application/octet-stream"
        if (mediaType.equals("")) {
            mediaType = "application/octet-stream";
        }

        return mediaType;
    }
309433
public static boolean isImage(String ext) {
        return "png".equals(ext) || "jpg".equals(ext) || "gif".equals(ext) || "svg".equals(ext);
    }
1343628
function extension (type) {
  if (!type || typeof type !== 'string') {
    return false
  }

  // TODO: use media-typer
  var match = EXTRACT_TYPE_REGEXP.exec(type)

  // get extensions
  var exts = match && exports.extensions[match[1].toLowerCase()]

  if (!exts || !exts.length) {
    return false
  }

  return exts[0]
}