Optimize mimeType detection when no mimeType is specified

Rebased #263 onto 4.0