首页 > 编程语言 > c/c++ > FindMimeFromData API判断文件MIME
2013
05-27

FindMimeFromData API判断文件MIME

/*

You can use the FindMimeFromData call to figure out what content-type to set when sending content via HTTP. FindMimeFromData allocates the content-type buffer for you, but don't attempt to free it. The content-type comes back in Unicode.

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;
}
最后编辑:
作者:NINE
这个作者貌似有点懒,什么都没有留下。

留下一个回复

你的email不会被公开。