GithubHelp home page GithubHelp logo

mimetypemap's Introduction

MimeTypeMap

English | 简体中文

Summary

Provides a huge two-way mapping of file extensions to mime types and mime types to file extensions, e.g.:

...
{".jpe", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/javascript"},
{".json", "application/json"},
...

Most mime types that have multiple possible extensions are pre-defined to get the most common extension when looking up extension by mime type. Since multiple extensions can map to the same mime type, it is not necessary that GetExtension(GetMimeType(ext)) returns the original extension - it will return the most common extension.

Originally posted on StackOverflow here: http://stackoverflow.com/questions/1029740/get-mime-type-from-filename-extension

NuGet

There are several packages on NuGet built from this repo. The official one is at this URL.

https://www.nuget.org/packages/MimeTypeMapOfficial

Note that the NuGet package sometimes lags behind the code in GitHub when there are contributions from others and I forget to update. If you find this to be the case and need some of the updates, create an issue here and I'll update NuGet.

Usage

After installation MimeTypeMap, include the following using statement in your class:

using MimeTypes;

Getting the mime type to an extension

Console.WriteLine("txt -> " + MimeTypeMap.GetMimeType("txt"));  // "text/plain"

Pass in a string extension and get a mime type back. Optionally include the period. If not it will be added before looking up the mime type.

If no mime type is found then the generic "application/octet-stream" is returned.

Getting the extension to a mime type

Console.WriteLine("audio/wav -> " + MimeTypeMap.GetExtension("audio/wav")); // ".wav"

Pass in a mime type and get an extension back. If the mime type is not registered, an error is thrown.

Collaboration & Contribution Principles

All code is licensed under MIT license.

Please submit pull requests for any additions while sticking to these principles for contributions:

  • MimeTypeMap.cs - the primary list of mime types
    • Maintain the existing groups of extension to mime type (primary is extension to mime-type)
    • Only add new mime-type to extension mappings if it is necessary to disambiguate the mapping based onreversing the extension to mime-type mappings.
    • Within each group of mappings, maintain alphabetical order by key.
    • Comments on a particular mapping should be on the same line after the mapping
      • Comments are optional.
      • Always keep comments in a single line regardless of length.
      • Comments to the source for less common mime-types are appreciated.
      • Non-obvious additions are validated before accepting a PR; a comment helps with this tremendously.
      • Comments must be in English. Do not worry about spelling or grammar if it is not your native language; I can correct comments and will still appreciate the comment. Translation with Google Translate is fine.
    • Do not change any code outside the mapping without asking about it first; you might waste your time otherwise.
    • All changes must maintain backwards compatibility. This includes changing what the mime-type to extension maps to unless the primary mapping is clearly wrong (far less common).
  • Project configuration changes
    • Changes to update the project to support the latest version of .NET are appreciated.
    • We must maintain backwards compatibility with all versions still commonly used in the wild.
  • CONTRIBUTORS acknowledgement and file
    • All contributions are greatly appreciated; both the individual contributions and of course the contributor.
    • Contributors are clearly visible on the GitHub project page.
    • Therefore there is no separate CONTRIBUTORS file to maintain.

Thank you,

Sam

mimetypemap's People

Contributors

0x1f9f1 avatar bjarmuz avatar christianackman avatar davebrothers avatar dbeuchler avatar dubrowgn avatar elychr avatar ezelargo avatar fawdlstty avatar hugohilario avatar hunteroi avatar ice1e0 avatar illfang avatar jimismith avatar jorrit avatar kaiseral avatar lajjne avatar lettucebo avatar paal123 avatar pekkanikander avatar rookev avatar samuelneff avatar seuleuzeuh avatar stefh avatar tomoneill avatar tsauvajon avatar veronikaandersen avatar william-gross avatar wongkayong avatar za-creature avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mimetypemap's Issues

mp3 each browser return differnt mime type

Today I encounter a strange behavior about matching mp3 mime type with browser return ContentType

and I have search an article: Which mime type should I use for mp3

Found out that each browser return different ContentType

if (!audio.ContentType.Equals(MimeTypeMap.GetMimeType(".mp3")))
{
    ViewBag.alert = "Incorrect,only accept *.mp3";
    return View(data);
}

using chrome will not be able to upload mp3 file

How do I get the .NET Core 2.0 version?

I tried getting the new .NET Core 2.0 version of this NuGet package but it doesn't show up in nuget.org even if I check include pre-release. How do I get it?

Suggestion: Windows Registry Fallback static method

I was browsing around and found this rather interesting MIME ContentType provider via the Windows Registry:

        private static string _GetContentTypeRegistry(string fileName)
        {
            var extension = Path.GetExtension(fileName);

            if (String.IsNullOrWhiteSpace(extension))
            {
                return null;
            }

            var registryKey = Registry.ClassesRoot.OpenSubKey(extension);

            if (registryKey == null)
            {
                return null;
            }

            var value = registryKey.GetValue("Content Type") as string;

            return String.IsNullOrWhiteSpace(value) ? null : value;
        }

It has already been stated before this method is system-specific and unreliable, but I feel as though it would be a good fallback alternative should something not be found in your MIMEType database.

Splitting the MIME Mapping into your original, this, and a validator which simply contains logic that if the Winodws Registry method returns null or "application/octlet-stream" (invalid), grab it from your Mappings database, seems like a more robust solution.

UAP compatible

Is it possible to build this package so it's useable with UAP Apps (Windows 10 Universal Apps)?

Case issue

Some of the items in the list are in mixed case, as far as I can tell TryGetValue is case sensitive so unless the extension is presented in exactly the right case it will fail. Was this intentional?

Mime type not recognize

Hi, I am having problems with extension "application/vnd.ms-outlook". I reviewed class MimeTypeMap.cs and it is there but for some reason I am getting an exception "Requested mime type is not registered: application/vnd.ms-outlook".

GetExtension should return null in case it didn't find the extension

This is not "mandatory" but would lead to a more friendly approach for a new user that comes across your package. Obviously, if the data is not found, you should never return a value (even if an empty string) as it may lead to strange behavior or misunderstanding.

I would highly recommend to introduce this breaking change in your library:

public static string GetExtension(string mimeType, bool throwErrorIfNotFound = true)
{
     ...

-    return string.Empty;
+    return null;
}

Enhancement | Have static content type class

It would be nice to have the string values (IE...application/json) of the content type setup in a static class. This would be handy to have for validating without having magic strings throughout the code.

GeoJson

Please consider adding .geojson, "application/geo+json"

New release to nuget?

It seems like the package on nuget is missing almost two years of work, are there any plans to update the package, or is the hope that people will just copy+past the code?

Recent commit introduced breaking changes and ambigous behavior

Commit ace145c added some breaking changes and also introduced some ambiguous behavior.

Breaking

GetMimeType("") previously returned "application/octet-stream" but now throws ArgumentNullException.

Ambiguous

GetMimeType used to take a file extension as input but now takes a file name or file extension. This can lead to some cases where it is not clear what the expected output should be.

Consider for example the string "gif". This could be a valid filename for a file without file extension and should in that case return "application/octet-stream". But it could also be interpreted as the file extension ".gif". To remove this ambiguity I suggest reverting to the previous behavior of expecting a file extension only.

Another option could be to change GetMimeType to expect a path string instead and then use System.IO.Path.GetExtension(path) to get the file extension before looking in the internal dictionary.

public static string GetMimeType(string path) {
    if (path == null) {
        throw new ArgumentNullException(nameof(path));
    }
    if (path != string.Empty && Path.GetFileName(path) == string.Empty) {
        throw new ArgumentException($"{path} is not a file path", nameof(path));
    }
    var ext = Path.GetExtension(path);
    return MimeTypeMap.TryGetMimeType(ext, out var result) ? result : DefaultMimeType;
}        

The following examples would then all be valid input:

  • GetMimeType(null) => throws ArgumentNullException
  • GetMimeType("") => "application/octet-stream"
  • GetMimeType(".") => "application/octet-stream"
  • GetMimeType("gif") => "application/octet-stream"
  • GetMimeType(".gif") => "image/gif"
  • GetMimeType("test.gif") => "image/gif"
  • GetMimeType("/test/image.gif") => "image/gif"
  • GetMimeType(@"C:\test") => "application/octet-stream"
  • GetMimeType(@"C:\test\") => throws ArgumentException
  • GetMimeType(@"C:\test\image.gif") => "image/gif"

Mime Type for .exe files

Using Microsoft's urlmon.dll to identify mime types will give you 'application/x-msdownload' for .exe files in Visual Studio 2019, but according to your mapping .exe files will give us 'application/octet-stream'.

No entry for .wasm files

.wasm (Web Assembly) files have the mime type application/wasm. This isn't in MimeTypeMap, but it should be.

Requested mime type is not registered: application/zip at MimeTypes.MimeTypeMap.GetExtension(String mimeType)

I tried to upload a zip file using my .net webapi but failed due to this. I made a util method to help me uploading files:

    private string GetExtensionFromFileHeader(HttpContent file)
    {
        return MimeTypeMap.GetExtension(file.Headers.ContentType.ToString());
    }

But it's crashing when I upload zip files (works fine with everything else I tried so far from images to pdfs and words)

Am I missing something?

i just called..

.. to say thank you ❤️. this just saved me a lot of time and is a great product! kudos to you and the committers.

everyone loves stevei

Official mimetypes vs. extension mapping for m4b files

Hello,

thank you for providing this useful library. Since I just ran into an issue using m4b files, I would like to ask, which sources you used for the mapping?

The result for m4b files is audio/m4b, but AFAIK this type does not exist / is not specified. The "official" list of registered Mimetypes linked to RFCs / Persons is available at:

https://www.iana.org/assignments/media-types/media-types.xhtml

These are without extension mapping, since the extension of a file can only be a hint for the real mimetype, although it maybe a good hint ;-)

The best resource I found WITH extension mapping was:
http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
which also lacks m4b :-/

Another good resource might be the magic.mgc which is common on Unix:
https://man7.org/linux/man-pages/man4/magic.4.html

Searching for m4b in the types definition, it is referenced as audio/x-m4b.

# grep 'm4b' /usr/share/mime/types
audio/x-m4b
# file -b --mime-type sample.m4b
audio/x-m4b

So it seems that in this library / type definition every custom mimetype, that is not referenced in the official listing, is prefixed with x-.

The magic.mgc contains a binary analysis instruction set, that does not rely on the extension, but this may also be incorrect (or at least unwanted), since the result for some m4b files is video/mp4, which is technically correct but assuming the extension is valid, the wanted result is audio/mp4 or better audio/x-m4b, even if the file contains the binary signature of a video.

To get to the bottom line:

  • The official mimetypes do not contain audio/m4b, which may be wrong in your library
  • The inofficial but commonly used mimetypes are usually prefixed with an /x- (e.g. audio/x-m4b)
  • What are your sources for the mappings?
  • Should I create a pull request to change the m4b result to audio/x-m4b or is this behaviour intended?

Redundent code

I don't understand why you didn't simply return mappings and have written this code?

`var cache = mappings.ToList(); // need ToList() to avoid modifying while still enumerating

        foreach (var mapping in cache)
        {
            if (!mappings.ContainsKey(mapping.Value))
            {
                mappings.Add(mapping.Value, mapping.Key);
            }
        }
        return mappings;`

When this is useful?

NuGet package not updated

Hello there!

It seems that 3 days ago, the NuGet package was updated. As you stated in #113, you also included a TryGetExtension method in your codebase. Unfortunately, it does not seem to be anywhere on Github nor in the package version 1.0.12.

Here are a few screenshots:

image
As you can see, it is the latest version available and there are no methods added nor XML documentation (even though TryGetMimeType was added with PR #114).

image
Here I cannot find the TryGetExtension method you were talking about in issue #113 .

image

Strong naming and signing missing

Unusable together with signed assemblies, resulting in

Could not load file or assembly 'MimeTypeMap, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)

Define TryGetMimeType & GetMimeType

Good afternoon!

I came across your repository while searching for a solution to make sure that the filename of a file matches its content-type.

I was wondering if it would be possible to implement TryGetMimeType & GetMimeType using your private _mappings variable.

You can find below the possible signature of such methods:

public static bool TryGetMimeType(string? fileName, [NotNullWhen(true)] out string? mimeType);

public static string GetMimeType(string filename);

Content-Type: application/x-msdos-program

Hello, I received an error message when I tried to download a file because the content type (application/x-msdos-program) does not exist in this project yet. For detailed information, you can have a look at the screenshots below. Expected was an .exe extension.
Bildschirmfoto 2020-07-06 um 11 41 40
Bildschirmfoto 2020-07-06 um 11 40 16

Nuget package using GitHub actions

Hello!

Thanks for you library, I found it useful. But the only problem it's not published to Nuget so I can't integrate it into my app easily. What do you think about publishing packages using GitHub action? Here is link: https://github.com/marketplace/actions/publish-nuget All you need is to login on https://www.nuget.org/ and create key, add yaml file with configuration to your solution. If it's not fine for you I can upload latest package to Nuget but it will be manual approach.

New mime types

Hello.
Can you please add F4V, GXF, MXF, ISMA and ISMV to the mime type list?
I know that the last two have the default mime type that is returned if the extension is not found in the map, but it is nice to have them there for completion purposes.
Thank you.

NU1701 returned on NUGet package in .Net Core 3.1, but functionality is perfect

When referencing the NUGet package in a .Net Core 3.1 project, the NU1701 warning is recieved:

warning NU1701: Package 'MediaTypeMap 2.1.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework '.NETCoreApp,Version=v3.1'. This package may not be fully compatible with your project.

This class works without issue; is it possible to have the NUGet package ”officially” support .net core 3.1?

NuGet package not updated

Can you please bump the nuget package. Several commits since 5/25/2021 are not included
with mimeTypes i need. Many thanks for your time on this.

Provide strong assembly name

Currently assembly could not be used with strong-typed libraries. It's easy to fix it, but it's on you.

Hmm, I found that similar request is open from sept 2015. It's 5 minutes to do, just create an snk file and add it in project properties.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.