Skip to content

Instantly share code, notes, and snippets.

@vpetkovic
Last active September 26, 2019 15:50
Show Gist options
  • Save vpetkovic/d6be494efbcec15aa35bdc8182d96e02 to your computer and use it in GitHub Desktop.
Save vpetkovic/d6be494efbcec15aa35bdc8182d96e02 to your computer and use it in GitHub Desktop.
To guess MIME type based on byte[]: https://github.com/hey-red/Mime
public class ValuesController : Controller
{
private readonly IMimeMappingService _mimeMappingService;
public ValuesController(IMimeMappingService mimeMappingService)
{
_mimeMappingService = mimeMappingService;
}
[HttpGet]
public string Get(string fileName)
{
\!h return _mimeMappingService.Map(fileName);
}
}
using HeyRed.Mime;
// (Optionally) You can set path to magic database file manually.
MimeGuesser.MagicFilePath = "/path/to/magic/file";
// Guess mime type of file(overloaded method takes byte array or stream as arg.)
MimeGuesser.GuessMimeType("path/to/file"); //=> image/jpeg
// Get extension of file(overloaded method takes byte array or stream as arg.)
MimeGuesser.GuessExtension("path/to/file"); //=> jpeg
// Get mime type and extension of file(overloaded method takes byte array or stream as arg.)
MimeGuesser.GuessFileType("path/to/file"); //=> FileType
// Advanced: Want more than just the mime type? Use the Magic class
string calc = @"C:\Windows\System32\calc.exe";
var magic = new Magic(MagicOpenFlags.MAGIC_NONE);
magic.Read(calc); //=> PE32+ executable (GUI) x86-64, for MS Windows
// Check encoding:
string textFile = @"F:\Temp\file.txt";
var magic = new Magic(MagicOpenFlags.MAGIC_MIME_ENCODING);
magic.Read(textFile); //=> Output: utf-8
using Microsoft.AspNetCore.StaticFiles;
public void ConfigureServices(IServiceCollection services)
{
\!h var provider = new FileExtensionContentTypeProvider();
\!h provider.Mappings.Add(".dnct", "application/dotnetcoretutorials");
\!h services.AddSingleton<IMimeMappingService>(new MimeMappingService(provider));
services.AddMvc();
}
public interface IMimeMappingService
{
string Map(string fileName);
}
public class MimeMappingService : IMimeMappingService
{
private readonly FileExtensionContentTypeProvider _contentTypeProvider;
public MimeMappingService(FileExtensionContentTypeProvider contentTypeProvider)
{
_contentTypeProvider = contentTypeProvider;
}
public string Map(string fileName)
{
string contentType;
if (!_contentTypeProvider.TryGetContentType(fileName, out contentType))
{
contentType = "application/octet-stream";
}
return contentType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment