(home | about | stats)

pwyky: FindMimeFromData

Windows has a mechanism that can look at the contents of a buffer and determine the appropriate content-type. The Microsoft site has an article that talks about how this works.

You can use the FindMimeFromData call to figure out what content-type to set when sending content via HTTP. Two important things to note:

The following code reads 256 or fewer bytes from a file, passes the buffer to FindMimeFromData and translates the content-type into ANSI.

#include <stdio.h>

#include <urlmon.h>

char *GetContentType(char *);

int main(int argc, char *argv[])
{
    char *sFilename = "c:\\foo.txt";
    char *sContentType = GetContentType(sFilename);
    free(sContentType);
}

char *GetContentType(char *sFilename)
{
    int hr = S_OK;
    LPWSTR swContentType = 0;

    FILE *fp = NULL;
    char *sBuffer[256];
    int iBytesRead = 0;
    int iUnicodeLen = 0;

    // Create buffer to hold ANSI translated content-type string.
    char *sANSIContentType = (char *) malloc(1024 * sizeof(char));
    if (!sANSIContentType)
    {
        return NULL;
    }

    memset(sANSIContentType, 0, sizeof(char) * 1024);

    // Read at most 256 bytes from the file.
    fp = fopen(sFilename, "r");
    if (!fp)
    {
        printf("Failed to open file.\n");
        return NULL;
    }

    memset(sBuffer, 0, sizeof(char) * 256);
    iBytesRead = fread(sBuffer, sizeof(char), 256, fp);

    // Try to deduce the content-type from the buffer.
    if ((hr = FindMimeFromData(NULL, NULL, sBuffer, 
        iBytesRead, NULL, 0, &swContentType, 0)))
    {
        printf("Failed to find mime type from buffer.\n");
        return NULL;
    }

    // Convert the content-type to ANSI.
    iUnicodeLen = WideCharToMultiByte(CP_ACP, 0, swContentType, 
        SysStringLen(swContentType), sANSIContentType, 1023, NULL, FALSE);
    printf("%s\n", sANSIContentType);

    return sANSIContentType;
}
www.mobilitytech.com owner. This is a pwyky site.