Am trying to get Mime type from extension like .html
should give back text/html
.
I know how to get Mime with file available but not other way. Is there a way to query mime from extension, at least known ones?
you need to use GContentType
inside GIO:
https://developer.gnome.org/gio/stable/gio-GContentType.html
and to be precise g_content_type_guess()
:
https://developer.gnome.org/gio/stable/gio-GContentType.html#g-content-type-guess
which takes either a file name, or the file contents, and returns the guessed content type; from there, you can use g_content_type_get_mime_type()
to get the MIME type for the content type.
this is an example for how to use g_content_type_guess()
:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gio/gio.h>
int
main (int argc, char *argv[])
{
const char *file_name = "test.html";
gboolean is_certain = FALSE;
char *content_type = g_content_type_guess (file_name, NULL, 0, &is_certain);
if (content_type != NULL)
{
char *mime_type = g_content_type_get_mime_type (content_type);
g_print ("Content type for file '%s': %s (certain: %s)\n"
"MIME type for content type: %s\n",
file_name,
content_type,
is_certain ? "yes" : "no",
mime_type);
g_free (mime_type);
}
g_free (content_type);
return EXIT_SUCCESS;
}
once compiled, the output on Linux is:
Content type for file 'test.html': text/html (certain: no)
MIME type for content type: text/html
explanation: on Linux, content type is a MIME type; this is not true on other platforms, that's why you must convert GContentType
strings to MIME type.
also, as you can see, just using the extension will set the boolean is certain flag, as an extension by itself is not enough to determine the accurate content type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With