This method check mimetype to define file extension.
        If it can't, it use original-format metadata.
320316
def get_file_extension(self, filepath):
        
        mtype = magic.from_file(filepath, mime=True)
        if type(mtype) == bytes:
            mtype = mtype.decode("utf-8")

        if mtype == "audio/mpeg":
            ext = ".mp3"
        elif mtype == "audio/x-wav":
            ext = ".wav"
        else:
            ext = "." + self.get("original-format")
        return ext
77134
def defaultExtension(self):
        """"""
        result = self.EXTERNAL_TYPES[self.typ]
        if not self.fileExtensions:
            return result
        if result in self.fileExtensions:
            return result
        return self.fileExtensions[0]
1204965
def parse_meta(filename, data):
    
    if "." not in filename:
        raise MetaParsingException(
            "Can't recognize type of your metadata ('%s')!" % filename
        )

    suffix = filename.rsplit(".", 1)[1].lower()

    if suffix not in SUPPORTED_FILES:
        raise MetaParsingException("Can't parse file of type '%s'!" % suffix)

    fp = validator.FieldParser()
    for key, val in SUPPORTED_FILES[suffix](data).items():
        fp.process(key, val)

    return fp.get_epublication()
539225
function (type, disposition) {
        Header.isHeader(type) && (type = type.value);
        Header.isHeader(disposition) && (disposition = disposition.value);

        // validate that the content type exists
        if (!(type && _.isString(type))) { return; }

        var normalised = mimeFormat.lookup(type),
            info = {};

        _.assign(info, {
            type: normalised.type, // sanitised mime type base
            format: normalised.format, // format specific to the type returned
            name: DEFAULT_RESPONSE_FILENAME,
            ext: mimeType.extension(normalised.source) || E, // file extension from sanitised content type
            charset: normalised.charset || UTF8,

            // also storing some meta info for possible debugging
            _originalContentType: type, // the user provided mime type
            _sanitisedContentType: normalised.source, // sanitised mime type
            _accuratelyDetected: !normalised.orphan // this being true implies worse case (raw render)
        });

        // build the file name from extension
        info.filename = info.name;
        info.ext && (info.filename += (DOT + info.ext));

        return info;
    }
1334656
public function checkMimeType($fileInfo)
    {
        $mime = $fileInfo->getMimetype();
        if ($mime != 'directory' && !in_array($mime, $this->getFileManager()->getExtensionsAllowed())) {
            return 'Mime type "' . $mime . '" not allowed for file "' . $fileInfo->getFilename() . '"';
        }

        return true;
    }
1343719
@OverrideOnDemand
  @Nullable
  protected String determineMimeType (@Nonnull final String sFilename, @Nonnull final IReadableResource aResource)
  {
    return MimeTypeInfoManager.getDefaultInstance ().getPrimaryMimeTypeStringForFilename (sFilename);
  }
328104
def check_format(actual_file,    # type: Union[Dict[Text, Any], List, Text]
                 input_formats,  # type: Union[List[Text], Text]
                 ontology        # type: Optional[Graph]
                ):  # type: (...) -> None
    
    for afile in aslist(actual_file):
        if not afile:
            continue
        if "format" not in afile:
            raise validate.ValidationException(
                u"File has no 'format' defined: {}".format(
                    json_dumps(afile, indent=4)))
        for inpf in aslist(input_formats):
            if afile["format"] == inpf or \
                    formatSubclassOf(afile["format"], inpf, ontology, set()):
                return
        raise validate.ValidationException(
            u"File has an incompatible format: {}".format(
                json_dumps(afile, indent=4)))
581232
public function isValidMime()
    {
        $extension = strtolower(pathinfo($this->tmpFile['name'], PATHINFO_EXTENSION));

        // we can't check filenames without an extension or no temp file path, let them pass validation.
        if (!$extension || !$this->tmpFile['tmp_name']) {
            return true;
        }

        $expectedMimes = $this->getExpectedMimeTypes($this->tmpFile);
        if (empty($expectedMimes)) {
            throw new MimeUploadValidatorException(
                sprintf('Could not find a MIME type for extension %s', $extension)
            );
        }

        $fileInfo = new finfo(FILEINFO_MIME_TYPE);
        $foundMime = $fileInfo->file($this->tmpFile['tmp_name']);
        if (!$foundMime) {
            throw new MimeUploadValidatorException(
                sprintf('Could not find a MIME type for file %s', $this->tmpFile['tmp_name'])
            );
        }

        foreach ($expectedMimes as $expected) {
            if ($this->compareMime($foundMime, $expected)) {
                return true;
            }
        }

        return false;
    }
637470
private String getMimeTypeFromFileExtension(String srcFile)
  {
    String srcFileLowCase = srcFile.toLowerCase();

    for (FileCompressionType compressionType : FileCompressionType.values())
    {
      if (srcFileLowCase.endsWith(compressionType.fileExtension))
      {
        return compressionType.mimeType + "/" +
               compressionType.mimeSubTypes.get(0);
      }
    }

    return null;
  }
435978
def get_mimetype(path):
        
        filename = os.path.split(path)[1]
        mimetype = mimetypes.guess_type(filename)[0]
        if mimetype is None:
            mimetype = 'text/x-plain'
        _logger().debug('mimetype detected: %s', mimetype)
        return mimetype
1020029
public function MapExtensionToMimeType($mime_type, $extension)
    {
        if (!isset($this->mime_type_to_extensions[$mime_type])) {
            $this->mime_type_to_extensions[$mime_type] = array($extension);
        } else {
            $this->mime_type_to_extensions[$mime_type][] = $extension;
        }

        return true;
    }
785912
def mime_type(self, path):
        """"""
        name, ext = os.path.splitext(path)
        return MIME_TYPES[ext]
809100
def IsBinary(self, filename):
		""""""
		mimetype = mimetypes.guess_type(filename)[0]
		if not mimetype:
			return False  # e.g. README, "real" binaries usually have an extension
		# special case for text files which don't start with text/
		if mimetype in TEXT_MIMETYPES:
			return False
		return not mimetype.startswith("text/")
75084
public function getExtensionFromMimeType($mimeType) {
        return isset($this->mimeTypeToExtension[$mimeType]) ? $this->mimeTypeToExtension[$mimeType] : null;
    }
904835
def mime(self):
        '''
        
        '''
        return self.metadata['ContentType'] if 'ContentType' in self.metadata else BaseEngine.get_mimetype(self.buffer)
349251
def determine_file_type(self, z):
        """"""

        mimetype = z.read('mimetype').decode('utf-8').strip()
        self.type = MIMEMAP[mimetype]
1051622
@SuppressWarnings("WeakerAccess")
	public static boolean isMimeType(@Nonnull final MimePart part, @Nonnull final String mimeType) {
		// Do not use part.isMimeType(String) as it is broken for MimeBodyPart
		// and does not really check the actual content type.

		try {
			final ContentType contentType = new ContentType(retrieveDataHandler(part).getContentType());
			return contentType.match(mimeType);
		} catch (final ParseException ex) {
			return retrieveContentType(part).equalsIgnoreCase(mimeType);
		}
	}