Rectangle 27 43

If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note those does not use the data in the file itself.

var mimetype = System.Web.MimeMapping.GetMimeMapping(<pathToFile>);

This does not answer the original question "if the file extension is incorrect or missing". GetMimeMapping just uses a static dictionary of extension and mime entries.

I would advise editting your comment to note that this internally uses the file extension, which is easily faked.

c# - Using .NET, how can you find the mime type of a file based on the...

c# mime mime-types
Rectangle 27 43

If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note those does not use the data in the file itself.

var mimetype = System.Web.MimeMapping.GetMimeMapping(<pathToFile>);

This does not answer the original question "if the file extension is incorrect or missing". GetMimeMapping just uses a static dictionary of extension and mime entries.

I would advise editting your comment to note that this internally uses the file extension, which is easily faked.

c# - Using .NET, how can you find the mime type of a file based on the...

c# mime mime-types
Rectangle 27 17

I've just converted my VB.NET class to C# to detect mime types. They will be identified by a mix of sniffing the first 256 Bytes of a file(urlmon.dll - f.e. used by internet explorer) and a set of known types.

You can also use it to check if the file is what it pretends to be(if the extension matches the type).

// check whether or not the uploaded file is an image:
var contentType = MimeTypes.GetContentType(FileUpload1.PostedFile.FileName);
if(contentType.StartsWith("image"))
{
    // do something with the image ...
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.IO;

public class MimeTypes
{
    private static List<string> knownTypes;

    private static Dictionary<string, string> mimeTypes;

    [DllImport("urlmon.dll", CharSet = CharSet.Auto)]
    private static extern UInt32 FindMimeFromData(
        UInt32 pBC, [MarshalAs(UnmanagedType.LPStr)]
        string pwzUrl, [MarshalAs(UnmanagedType.LPArray)]
        byte[] pBuffer, UInt32 cbSize, [MarshalAs(UnmanagedType.LPStr)]
        string pwzMimeProposed, UInt32 dwMimeFlags, ref UInt32 ppwzMimeOut, UInt32 dwReserverd
    );

    public static string GetContentType(string fileName)
    {
        if (knownTypes == null || mimeTypes == null)
            InitializeMimeTypeLists();
        string contentType = "";
        string extension = System.IO.Path.GetExtension(fileName).Replace(".", "").ToLower();
        mimeTypes.TryGetValue(extension, out contentType);
        if (string.IsNullOrEmpty(contentType) || knownTypes.Contains(contentType))
        {
            string headerType = ScanFileForMimeType(fileName);
            if (headerType != "application/octet-stream" || string.IsNullOrEmpty(contentType))
                contentType = headerType;
        }
        return contentType;
    }

    private static string ScanFileForMimeType(string fileName)
    {
        try
        {
            byte[] buffer = new byte[256];
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                int readLength = Convert.ToInt32(Math.Min(256, fs.Length));
                fs.Read(buffer, 0, readLength);
            }

            UInt32 mimeType = default(UInt32);
            FindMimeFromData(0, null, buffer, 256, null, 0, ref mimeType, 0);
            IntPtr mimeTypePtr = new IntPtr(mimeType);
            string mime = Marshal.PtrToStringUni(mimeTypePtr);
            Marshal.FreeCoTaskMem(mimeTypePtr);
            if (string.IsNullOrEmpty(mime))
                mime = "application/octet-stream";
            return mime;
        } catch (Exception ex)
        {
            return "application/octet-stream";
        }
    }

    private static void InitializeMimeTypeLists()
    {
        knownTypes = new string[] {
        "text/plain",
        "text/html",
        "text/xml",
        "text/richtext",
        "text/scriptlet",
        "audio/x-aiff",
        "audio/basic",
        "audio/mid",
        "audio/wav",
        "image/gif",
        "image/jpeg",
        "image/pjpeg",
        "image/png",
        "image/x-png",
        "image/tiff",
        "image/bmp",
        "image/x-xbitmap",
        "image/x-jg",
        "image/x-emf",
        "image/x-wmf",
        "video/avi",
        "video/mpeg",
        "application/octet-stream",
        "application/postscript",
        "application/base64",
        "application/macbinhex40",
        "application/pdf",
        "application/xml",
        "application/atom+xml",
        "application/rss+xml",
        "application/x-compressed",
        "application/x-zip-compressed",
        "application/x-gzip-compressed",
        "application/java",
        "application/x-msdownload"
    }.ToList();

        mimeTypes = new Dictionary<string, string>();
        mimeTypes.Add("3dm", "x-world/x-3dmf");
        mimeTypes.Add("3dmf", "x-world/x-3dmf");
        mimeTypes.Add("a", "application/octet-stream");
        mimeTypes.Add("aab", "application/x-authorware-bin");
        mimeTypes.Add("aam", "application/x-authorware-map");
        mimeTypes.Add("aas", "application/x-authorware-seg");
        mimeTypes.Add("abc", "text/vnd.abc");
        mimeTypes.Add("acgi", "text/html");
        mimeTypes.Add("afl", "video/animaflex");
        mimeTypes.Add("ai", "application/postscript");
        mimeTypes.Add("aif", "audio/aiff");
        mimeTypes.Add("aifc", "audio/aiff");
        mimeTypes.Add("aiff", "audio/aiff");
        mimeTypes.Add("aim", "application/x-aim");
        mimeTypes.Add("aip", "text/x-audiosoft-intra");
        mimeTypes.Add("ani", "application/x-navi-animation");
        mimeTypes.Add("aos", "application/x-nokia-9000-communicator-add-on-software");
        mimeTypes.Add("aps", "application/mime");
        mimeTypes.Add("arc", "application/octet-stream");
        mimeTypes.Add("arj", "application/arj");
        mimeTypes.Add("art", "image/x-jg");
        mimeTypes.Add("asf", "video/x-ms-asf");
        mimeTypes.Add("asm", "text/x-asm");
        mimeTypes.Add("asp", "text/asp");
        mimeTypes.Add("asx", "application/x-mplayer2");
        mimeTypes.Add("au", "audio/basic");
        mimeTypes.Add("avi", "video/avi");
        mimeTypes.Add("avs", "video/avs-video");
        mimeTypes.Add("bcpio", "application/x-bcpio");
        mimeTypes.Add("bin", "application/octet-stream");
        mimeTypes.Add("bm", "image/bmp");
        mimeTypes.Add("bmp", "image/bmp");
        mimeTypes.Add("boo", "application/book");
        mimeTypes.Add("book", "application/book");
        mimeTypes.Add("boz", "application/x-bzip2");
        mimeTypes.Add("bsh", "application/x-bsh");
        mimeTypes.Add("bz", "application/x-bzip");
        mimeTypes.Add("bz2", "application/x-bzip2");
        mimeTypes.Add("c", "text/plain");
        mimeTypes.Add("c++", "text/plain");
        mimeTypes.Add("cat", "application/vnd.ms-pki.seccat");
        mimeTypes.Add("cc", "text/plain");
        mimeTypes.Add("ccad", "application/clariscad");
        mimeTypes.Add("cco", "application/x-cocoa");
        mimeTypes.Add("cdf", "application/cdf");
        mimeTypes.Add("cer", "application/pkix-cert");
        mimeTypes.Add("cha", "application/x-chat");
        mimeTypes.Add("chat", "application/x-chat");
        mimeTypes.Add("class", "application/java");
        mimeTypes.Add("com", "application/octet-stream");
        mimeTypes.Add("conf", "text/plain");
        mimeTypes.Add("cpio", "application/x-cpio");
        mimeTypes.Add("cpp", "text/x-c");
        mimeTypes.Add("cpt", "application/x-cpt");
        mimeTypes.Add("crl", "application/pkcs-crl");
        mimeTypes.Add("css", "text/css");
        mimeTypes.Add("def", "text/plain");
        mimeTypes.Add("der", "application/x-x509-ca-cert");
        mimeTypes.Add("dif", "video/x-dv");
        mimeTypes.Add("dir", "application/x-director");
        mimeTypes.Add("dl", "video/dl");
        mimeTypes.Add("doc", "application/msword");
        mimeTypes.Add("dot", "application/msword");
        mimeTypes.Add("dp", "application/commonground");
        mimeTypes.Add("drw", "application/drafting");
        mimeTypes.Add("dump", "application/octet-stream");
        mimeTypes.Add("dv", "video/x-dv");
        mimeTypes.Add("dvi", "application/x-dvi");
        mimeTypes.Add("dwf", "drawing/x-dwf (old)");
        mimeTypes.Add("dwg", "application/acad");
        mimeTypes.Add("dxf", "application/dxf");
        mimeTypes.Add("eps", "application/postscript");
        mimeTypes.Add("es", "application/x-esrehber");
        mimeTypes.Add("etx", "text/x-setext");
        mimeTypes.Add("evy", "application/envoy");
        mimeTypes.Add("exe", "application/octet-stream");
        mimeTypes.Add("f", "text/plain");
        mimeTypes.Add("f90", "text/x-fortran");
        mimeTypes.Add("fdf", "application/vnd.fdf");
        mimeTypes.Add("fif", "image/fif");
        mimeTypes.Add("fli", "video/fli");
        mimeTypes.Add("flv", "video/x-flv");
        mimeTypes.Add("for", "text/x-fortran");
        mimeTypes.Add("fpx", "image/vnd.fpx");
        mimeTypes.Add("g", "text/plain");
        mimeTypes.Add("g3", "image/g3fax");
        mimeTypes.Add("gif", "image/gif");
        mimeTypes.Add("gl", "video/gl");
        mimeTypes.Add("gsd", "audio/x-gsm");
        mimeTypes.Add("gtar", "application/x-gtar");
        mimeTypes.Add("gz", "application/x-compressed");
        mimeTypes.Add("h", "text/plain");
        mimeTypes.Add("help", "application/x-helpfile");
        mimeTypes.Add("hgl", "application/vnd.hp-hpgl");
        mimeTypes.Add("hh", "text/plain");
        mimeTypes.Add("hlp", "application/x-winhelp");
        mimeTypes.Add("htc", "text/x-component");
        mimeTypes.Add("htm", "text/html");
        mimeTypes.Add("html", "text/html");
        mimeTypes.Add("htmls", "text/html");
        mimeTypes.Add("htt", "text/webviewhtml");
        mimeTypes.Add("htx", "text/html");
        mimeTypes.Add("ice", "x-conference/x-cooltalk");
        mimeTypes.Add("ico", "image/x-icon");
        mimeTypes.Add("idc", "text/plain");
        mimeTypes.Add("ief", "image/ief");
        mimeTypes.Add("iefs", "image/ief");
        mimeTypes.Add("iges", "application/iges");
        mimeTypes.Add("igs", "application/iges");
        mimeTypes.Add("ima", "application/x-ima");
        mimeTypes.Add("imap", "application/x-httpd-imap");
        mimeTypes.Add("inf", "application/inf");
        mimeTypes.Add("ins", "application/x-internett-signup");
        mimeTypes.Add("ip", "application/x-ip2");
        mimeTypes.Add("isu", "video/x-isvideo");
        mimeTypes.Add("it", "audio/it");
        mimeTypes.Add("iv", "application/x-inventor");
        mimeTypes.Add("ivr", "i-world/i-vrml");
        mimeTypes.Add("ivy", "application/x-livescreen");
        mimeTypes.Add("jam", "audio/x-jam");
        mimeTypes.Add("jav", "text/plain");
        mimeTypes.Add("java", "text/plain");
        mimeTypes.Add("jcm", "application/x-java-commerce");
        mimeTypes.Add("jfif", "image/jpeg");
        mimeTypes.Add("jfif-tbnl", "image/jpeg");
        mimeTypes.Add("jpe", "image/jpeg");
        mimeTypes.Add("jpeg", "image/jpeg");
        mimeTypes.Add("jpg", "image/jpeg");
        mimeTypes.Add("jps", "image/x-jps");
        mimeTypes.Add("js", "application/x-javascript");
        mimeTypes.Add("jut", "image/jutvision");
        mimeTypes.Add("kar", "audio/midi");
        mimeTypes.Add("ksh", "application/x-ksh");
        mimeTypes.Add("la", "audio/nspaudio");
        mimeTypes.Add("lam", "audio/x-liveaudio");
        mimeTypes.Add("latex", "application/x-latex");
        mimeTypes.Add("lha", "application/lha");
        mimeTypes.Add("lhx", "application/octet-stream");
        mimeTypes.Add("list", "text/plain");
        mimeTypes.Add("lma", "audio/nspaudio");
        mimeTypes.Add("log", "text/plain");
        mimeTypes.Add("lsp", "application/x-lisp");
        mimeTypes.Add("lst", "text/plain");
        mimeTypes.Add("lsx", "text/x-la-asf");
        mimeTypes.Add("ltx", "application/x-latex");
        mimeTypes.Add("lzh", "application/octet-stream");
        mimeTypes.Add("lzx", "application/lzx");
        mimeTypes.Add("m", "text/plain");
        mimeTypes.Add("m1v", "video/mpeg");
        mimeTypes.Add("m2a", "audio/mpeg");
        mimeTypes.Add("m2v", "video/mpeg");
        mimeTypes.Add("m3u", "audio/x-mpequrl");
        mimeTypes.Add("man", "application/x-troff-man");
        mimeTypes.Add("map", "application/x-navimap");
        mimeTypes.Add("mar", "text/plain");
        mimeTypes.Add("mbd", "application/mbedlet");
        mimeTypes.Add("mc$", "application/x-magic-cap-package-1.0");
        mimeTypes.Add("mcd", "application/mcad");
        mimeTypes.Add("mcf", "image/vasa");
        mimeTypes.Add("mcp", "application/netmc");
        mimeTypes.Add("me", "application/x-troff-me");
        mimeTypes.Add("mht", "message/rfc822");
        mimeTypes.Add("mhtml", "message/rfc822");
        mimeTypes.Add("mid", "audio/midi");
        mimeTypes.Add("midi", "audio/midi");
        mimeTypes.Add("mif", "application/x-frame");
        mimeTypes.Add("mime", "message/rfc822");
        mimeTypes.Add("mjf", "audio/x-vnd.audioexplosion.mjuicemediafile");
        mimeTypes.Add("mjpg", "video/x-motion-jpeg");
        mimeTypes.Add("mm", "application/base64");
        mimeTypes.Add("mme", "application/base64");
        mimeTypes.Add("mod", "audio/mod");
        mimeTypes.Add("moov", "video/quicktime");
        mimeTypes.Add("mov", "video/quicktime");
        mimeTypes.Add("movie", "video/x-sgi-movie");
        mimeTypes.Add("mp2", "audio/mpeg");
        mimeTypes.Add("mp3", "audio/mpeg3");
        mimeTypes.Add("mpa", "audio/mpeg");
        mimeTypes.Add("mpc", "application/x-project");
        mimeTypes.Add("mpe", "video/mpeg");
        mimeTypes.Add("mpeg", "video/mpeg");
        mimeTypes.Add("mpg", "video/mpeg");
        mimeTypes.Add("mpga", "audio/mpeg");
        mimeTypes.Add("mpp", "application/vnd.ms-project");
        mimeTypes.Add("mpt", "application/x-project");
        mimeTypes.Add("mpv", "application/x-project");
        mimeTypes.Add("mpx", "application/x-project");
        mimeTypes.Add("mrc", "application/marc");
        mimeTypes.Add("ms", "application/x-troff-ms");
        mimeTypes.Add("mv", "video/x-sgi-movie");
        mimeTypes.Add("my", "audio/make");
        mimeTypes.Add("mzz", "application/x-vnd.audioexplosion.mzz");
        mimeTypes.Add("nap", "image/naplps");
        mimeTypes.Add("naplps", "image/naplps");
        mimeTypes.Add("nc", "application/x-netcdf");
        mimeTypes.Add("ncm", "application/vnd.nokia.configuration-message");
        mimeTypes.Add("nif", "image/x-niff");
        mimeTypes.Add("niff", "image/x-niff");
        mimeTypes.Add("nix", "application/x-mix-transfer");
        mimeTypes.Add("nsc", "application/x-conference");
        mimeTypes.Add("nvd", "application/x-navidoc");
        mimeTypes.Add("o", "application/octet-stream");
        mimeTypes.Add("oda", "application/oda");
        mimeTypes.Add("omc", "application/x-omc");
        mimeTypes.Add("omcd", "application/x-omcdatamaker");
        mimeTypes.Add("omcr", "application/x-omcregerator");
        mimeTypes.Add("p", "text/x-pascal");
        mimeTypes.Add("p10", "application/pkcs10");
        mimeTypes.Add("p12", "application/pkcs-12");
        mimeTypes.Add("p7a", "application/x-pkcs7-signature");
        mimeTypes.Add("p7c", "application/pkcs7-mime");
        mimeTypes.Add("pas", "text/pascal");
        mimeTypes.Add("pbm", "image/x-portable-bitmap");
        mimeTypes.Add("pcl", "application/vnd.hp-pcl");
        mimeTypes.Add("pct", "image/x-pict");
        mimeTypes.Add("pcx", "image/x-pcx");
        mimeTypes.Add("pdf", "application/pdf");
        mimeTypes.Add("pfunk", "audio/make");
        mimeTypes.Add("pgm", "image/x-portable-graymap");
        mimeTypes.Add("pic", "image/pict");
        mimeTypes.Add("pict", "image/pict");
        mimeTypes.Add("pkg", "application/x-newton-compatible-pkg");
        mimeTypes.Add("pko", "application/vnd.ms-pki.pko");
        mimeTypes.Add("pl", "text/plain");
        mimeTypes.Add("plx", "application/x-pixclscript");
        mimeTypes.Add("pm", "image/x-xpixmap");
        mimeTypes.Add("png", "image/png");
        mimeTypes.Add("pnm", "application/x-portable-anymap");
        mimeTypes.Add("pot", "application/mspowerpoint");
        mimeTypes.Add("pov", "model/x-pov");
        mimeTypes.Add("ppa", "application/vnd.ms-powerpoint");
        mimeTypes.Add("ppm", "image/x-portable-pixmap");
        mimeTypes.Add("pps", "application/mspowerpoint");
        mimeTypes.Add("ppt", "application/mspowerpoint");
        mimeTypes.Add("ppz", "application/mspowerpoint");
        mimeTypes.Add("pre", "application/x-freelance");
        mimeTypes.Add("prt", "application/pro_eng");
        mimeTypes.Add("ps", "application/postscript");
        mimeTypes.Add("psd", "application/octet-stream");
        mimeTypes.Add("pvu", "paleovu/x-pv");
        mimeTypes.Add("pwz", "application/vnd.ms-powerpoint");
        mimeTypes.Add("py", "text/x-script.phyton");
        mimeTypes.Add("pyc", "applicaiton/x-bytecode.python");
        mimeTypes.Add("qcp", "audio/vnd.qcelp");
        mimeTypes.Add("qd3", "x-world/x-3dmf");
        mimeTypes.Add("qd3d", "x-world/x-3dmf");
        mimeTypes.Add("qif", "image/x-quicktime");
        mimeTypes.Add("qt", "video/quicktime");
        mimeTypes.Add("qtc", "video/x-qtc");
        mimeTypes.Add("qti", "image/x-quicktime");
        mimeTypes.Add("qtif", "image/x-quicktime");
        mimeTypes.Add("ra", "audio/x-pn-realaudio");
        mimeTypes.Add("ram", "audio/x-pn-realaudio");
        mimeTypes.Add("ras", "application/x-cmu-raster");
        mimeTypes.Add("rast", "image/cmu-raster");
        mimeTypes.Add("rexx", "text/x-script.rexx");
        mimeTypes.Add("rf", "image/vnd.rn-realflash");
        mimeTypes.Add("rgb", "image/x-rgb");
        mimeTypes.Add("rm", "application/vnd.rn-realmedia");
        mimeTypes.Add("rmi", "audio/mid");
        mimeTypes.Add("rmm", "audio/x-pn-realaudio");
        mimeTypes.Add("rmp", "audio/x-pn-realaudio");
        mimeTypes.Add("rng", "application/ringing-tones");
        mimeTypes.Add("rnx", "application/vnd.rn-realplayer");
        mimeTypes.Add("roff", "application/x-troff");
        mimeTypes.Add("rp", "image/vnd.rn-realpix");
        mimeTypes.Add("rpm", "audio/x-pn-realaudio-plugin");
        mimeTypes.Add("rt", "text/richtext");
        mimeTypes.Add("rtf", "text/richtext");
        mimeTypes.Add("rtx", "application/rtf");
        mimeTypes.Add("rv", "video/vnd.rn-realvideo");
        mimeTypes.Add("s", "text/x-asm");
        mimeTypes.Add("s3m", "audio/s3m");
        mimeTypes.Add("saveme", "application/octet-stream");
        mimeTypes.Add("sbk", "application/x-tbook");
        mimeTypes.Add("scm", "application/x-lotusscreencam");
        mimeTypes.Add("sdml", "text/plain");
        mimeTypes.Add("sdp", "application/sdp");
        mimeTypes.Add("sdr", "application/sounder");
        mimeTypes.Add("sea", "application/sea");
        mimeTypes.Add("set", "application/set");
        mimeTypes.Add("sgm", "text/sgml");
        mimeTypes.Add("sgml", "text/sgml");
        mimeTypes.Add("sh", "application/x-bsh");
        mimeTypes.Add("shtml", "text/html");
        mimeTypes.Add("sid", "audio/x-psid");
        mimeTypes.Add("sit", "application/x-sit");
        mimeTypes.Add("skd", "application/x-koan");
        mimeTypes.Add("skm", "application/x-koan");
        mimeTypes.Add("skp", "application/x-koan");
        mimeTypes.Add("skt", "application/x-koan");
        mimeTypes.Add("sl", "application/x-seelogo");
        mimeTypes.Add("smi", "application/smil");
        mimeTypes.Add("smil", "application/smil");
        mimeTypes.Add("snd", "audio/basic");
        mimeTypes.Add("sol", "application/solids");
        mimeTypes.Add("spc", "application/x-pkcs7-certificates");
        mimeTypes.Add("spl", "application/futuresplash");
        mimeTypes.Add("spr", "application/x-sprite");
        mimeTypes.Add("sprite", "application/x-sprite");
        mimeTypes.Add("src", "application/x-wais-source");
        mimeTypes.Add("ssi", "text/x-server-parsed-html");
        mimeTypes.Add("ssm", "application/streamingmedia");
        mimeTypes.Add("sst", "application/vnd.ms-pki.certstore");
        mimeTypes.Add("step", "application/step");
        mimeTypes.Add("stl", "application/sla");
        mimeTypes.Add("stp", "application/step");
        mimeTypes.Add("sv4cpio", "application/x-sv4cpio");
        mimeTypes.Add("sv4crc", "application/x-sv4crc");
        mimeTypes.Add("svf", "image/vnd.dwg");
        mimeTypes.Add("svr", "application/x-world");
        mimeTypes.Add("swf", "application/x-shockwave-flash");
        mimeTypes.Add("t", "application/x-troff");
        mimeTypes.Add("talk", "text/x-speech");
        mimeTypes.Add("tar", "application/x-tar");
        mimeTypes.Add("tbk", "application/toolbook");
        mimeTypes.Add("tcl", "application/x-tcl");
        mimeTypes.Add("tcsh", "text/x-script.tcsh");
        mimeTypes.Add("tex", "application/x-tex");
        mimeTypes.Add("texi", "application/x-texinfo");
        mimeTypes.Add("texinfo", "application/x-texinfo");
        mimeTypes.Add("text", "text/plain");
        mimeTypes.Add("tgz", "application/x-compressed");
        mimeTypes.Add("tif", "image/tiff");
        mimeTypes.Add("tr", "application/x-troff");
        mimeTypes.Add("tsi", "audio/tsp-audio");
        mimeTypes.Add("tsp", "audio/tsplayer");
        mimeTypes.Add("tsv", "text/tab-separated-values");
        mimeTypes.Add("turbot", "image/florian");
        mimeTypes.Add("txt", "text/plain");
        mimeTypes.Add("uil", "text/x-uil");
        mimeTypes.Add("uni", "text/uri-list");
        mimeTypes.Add("unis", "text/uri-list");
        mimeTypes.Add("unv", "application/i-deas");
        mimeTypes.Add("uri", "text/uri-list");
        mimeTypes.Add("uris", "text/uri-list");
        mimeTypes.Add("ustar", "application/x-ustar");
        mimeTypes.Add("uu", "application/octet-stream");
        mimeTypes.Add("vcd", "application/x-cdlink");
        mimeTypes.Add("vcs", "text/x-vcalendar");
        mimeTypes.Add("vda", "application/vda");
        mimeTypes.Add("vdo", "video/vdo");
        mimeTypes.Add("vew", "application/groupwise");
        mimeTypes.Add("viv", "video/vivo");
        mimeTypes.Add("vivo", "video/vivo");
        mimeTypes.Add("vmd", "application/vocaltec-media-desc");
        mimeTypes.Add("vmf", "application/vocaltec-media-file");
        mimeTypes.Add("voc", "audio/voc");
        mimeTypes.Add("vos", "video/vosaic");
        mimeTypes.Add("vox", "audio/voxware");
        mimeTypes.Add("vqe", "audio/x-twinvq-plugin");
        mimeTypes.Add("vqf", "audio/x-twinvq");
        mimeTypes.Add("vql", "audio/x-twinvq-plugin");
        mimeTypes.Add("vrml", "application/x-vrml");
        mimeTypes.Add("vrt", "x-world/x-vrt");
        mimeTypes.Add("vsd", "application/x-visio");
        mimeTypes.Add("vst", "application/x-visio");
        mimeTypes.Add("vsw", "application/x-visio");
        mimeTypes.Add("w60", "application/wordperfect6.0");
        mimeTypes.Add("w61", "application/wordperfect6.1");
        mimeTypes.Add("w6w", "application/msword");
        mimeTypes.Add("wav", "audio/wav");
        mimeTypes.Add("wb1", "application/x-qpro");
        mimeTypes.Add("wbmp", "image/vnd.wap.wbmp");
        mimeTypes.Add("web", "application/vnd.xara");
        mimeTypes.Add("wiz", "application/msword");
        mimeTypes.Add("wk1", "application/x-123");
        mimeTypes.Add("wmf", "windows/metafile");
        mimeTypes.Add("wml", "text/vnd.wap.wml");
        mimeTypes.Add("wmlc", "application/vnd.wap.wmlc");
        mimeTypes.Add("wmls", "text/vnd.wap.wmlscript");
        mimeTypes.Add("wmlsc", "application/vnd.wap.wmlscriptc");
        mimeTypes.Add("word", "application/msword");
        mimeTypes.Add("wp", "application/wordperfect");
        mimeTypes.Add("wp5", "application/wordperfect");
        mimeTypes.Add("wp6", "application/wordperfect");
        mimeTypes.Add("wpd", "application/wordperfect");
        mimeTypes.Add("wq1", "application/x-lotus");
        mimeTypes.Add("wri", "application/mswrite");
        mimeTypes.Add("wrl", "application/x-world");
        mimeTypes.Add("wrz", "model/vrml");
        mimeTypes.Add("wsc", "text/scriplet");
        mimeTypes.Add("wsrc", "application/x-wais-source");
        mimeTypes.Add("wtk", "application/x-wintalk");
        mimeTypes.Add("xbm", "image/x-xbitmap");
        mimeTypes.Add("xdr", "video/x-amt-demorun");
        mimeTypes.Add("xgz", "xgl/drawing");
        mimeTypes.Add("xif", "image/vnd.xiff");
        mimeTypes.Add("xl", "application/excel");
        mimeTypes.Add("xla", "application/excel");
        mimeTypes.Add("xlb", "application/excel");
        mimeTypes.Add("xlc", "application/excel");
        mimeTypes.Add("xld", "application/excel");
        mimeTypes.Add("xlk", "application/excel");
        mimeTypes.Add("xll", "application/excel");
        mimeTypes.Add("xlm", "application/excel");
        mimeTypes.Add("xls", "application/excel");
        mimeTypes.Add("xlsx", "application/excel");
        mimeTypes.Add("xlt", "application/excel");
        mimeTypes.Add("xlv", "application/excel");
        mimeTypes.Add("xlw", "application/excel");
        mimeTypes.Add("xm", "audio/xm");
        mimeTypes.Add("xml", "text/xml");
        mimeTypes.Add("xmz", "xgl/movie");
        mimeTypes.Add("xpix", "application/x-vnd.ls-xpix");
        mimeTypes.Add("xpm", "image/x-xpixmap");
        mimeTypes.Add("x-png", "image/png");
        mimeTypes.Add("xsr", "video/x-amt-showrun");
        mimeTypes.Add("xwd", "image/x-xwd");
        mimeTypes.Add("xyz", "chemical/x-pdb");
        mimeTypes.Add("z", "application/x-compress");
        mimeTypes.Add("zip", "application/x-compressed");
        mimeTypes.Add("zoo", "application/octet-stream");
        mimeTypes.Add("zsh", "text/x-script.zsh");
    }
}

You have to update this list when a mime type is unknown and it is not sufficient to know that it is application/octet-stream. It might suffice to check if an extension is txt but the mime-type is binary data, because that means that this file is not what it pretends to be.

Apart from that it's really easier to use a RegularExpressionValidator.

<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" 
 Text="Upload File" />&nbsp;<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:RegularExpressionValidator 
 id="RegularExpressionValidator1" runat="server" 
 ErrorMessage="Only jpeg files are allowed!" 
 ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))
    +(.jpg|.JPG|.jpeg|.JPEG)$" 
 ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>
if (FileUpload1.HasFile)
{
    string fileExt = 
       System.IO.Path.GetExtension(FileUpload1.FileName);

    if (fileExt == ".jpeg" || fileExt == ".jpg")
    {
        //do what you want with this image
    }
    else
    {
        Label1.Text = "Only .jpeg files are allowed!";
    }
}

This is excellent !!!.A quick question here. If an exe file is saved as .jpg file by changing the extension, how good is the approach using regular expression.

@YagyaSharma: The RegularExpression approach just checks the the FileName of the FileUpload control. So there is no "deep-check" at all. But you only have to use my MimeTypes class on serverside. ScanFileForMimeType will show that it's not an image type but an application/octet-stream.

I have used the approach of MIME type to implement this functionality. However, as soon as I select the exe file from the file selection dialog, the page is refreshed and comes up with the error message "The page can't be displayed". Any idea why this may be happening. Regards - Yagya

So are you sure that the file is not simply to large? The default max request size is 4MB. You can change a setting in your web.config to allow larger requests. the maxRequestLength attribute of the httpRuntime element controls that, which you can change in the web.config file. This link shows the schema for the httpRuntime element: msdn2.microsoft.com/en-us/library/e1f13641(VS.80).aspx

This blog talks about some issues with the urlmon method and gives remedial code. He's not very good at copy/paste it seems but his refactoring has some tweaks to make it safer (as claimed by author).

Determine the file type using C# - Stack Overflow

c#
Rectangle 27 15

So the base idea is that this code uses File Objects, for more info on them see :

As specified per w3, the type attribute of the File object is a MIME type. This is defined in the RFC 2046. But the spec itself isn't the most interesting part, what's more interesting is the list of the existing MIME type here or the most used one here.

In this code, they use the type attribute and execute a regexp on it (see match and RegExp for more info). Their regexp says that it's ok if the type contains image.

To make your own selector, you'll have to combine the above. (some of the example use === instead of match because the mime type is the entire type) For example the following check are possible:

  • document (not pdf only, odt have this type as well for example) : input.files[0].type==='application/pdf'
input.files[0].type.match('audio.*')
input.files[0].type.match('video.*')

After that you can use a selector on the name attribute of the file if you wish to match only certain extension (for example to check between different kind of document, you could look if it's a .pdf, a .odt ...) using for example input.files[0].name.match('\.pdf'). But imho that's not advised, as the user could easily play with that (removing or changing them).

Its working as I tried for PDF :) Thanks

'image' one and it worked a charm! if(!file.type.match(/^image\//) && !file.type.match(/^video\//)){ };

Might be worth mentioning this isn't a 100% complete solution. For example, file.type of a sample .mkv file I have is an empty string.

javascript - JS and type.match as file mime type - need advice - Stack...

javascript firefox google-chrome file-io fileapi
Rectangle 27 15

So the base idea is that this code uses File Objects, for more info on them see :

As specified per w3, the type attribute of the File object is a MIME type. This is defined in the RFC 2046. But the spec itself isn't the most interesting part, what's more interesting is the list of the existing MIME type here or the most used one here.

In this code, they use the type attribute and execute a regexp on it (see match and RegExp for more info). Their regexp says that it's ok if the type contains image.

To make your own selector, you'll have to combine the above. (some of the example use === instead of match because the mime type is the entire type) For example the following check are possible:

  • document (not pdf only, odt have this type as well for example) : input.files[0].type==='application/pdf'
input.files[0].type.match('audio.*')
input.files[0].type.match('video.*')

After that you can use a selector on the name attribute of the file if you wish to match only certain extension (for example to check between different kind of document, you could look if it's a .pdf, a .odt ...) using for example input.files[0].name.match('\.pdf'). But imho that's not advised, as the user could easily play with that (removing or changing them).

Its working as I tried for PDF :) Thanks

'image' one and it worked a charm! if(!file.type.match(/^image\//) && !file.type.match(/^video\//)){ };

Might be worth mentioning this isn't a 100% complete solution. For example, file.type of a sample .mkv file I have is an empty string.

javascript - JS and type.match as file mime type - need advice - Stack...

javascript firefox google-chrome file-io fileapi
Rectangle 27 43

If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.

var mimetype = System.Web.MimeMapping.GetMimeMapping(<pathToFile>);

This does not answer the original question "if the file extension is incorrect or missing". GetMimeMapping just uses a static dictionary of extension and mime entries.

I would advise editting your comment to note that this internally uses the file extension, which is easily faked.

c# - Using .NET, how can you find the mime type of a file based on the...

c# mime mime-types
Rectangle 27 43

If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.

var mimetype = System.Web.MimeMapping.GetMimeMapping(<pathToFile>);

This does not answer the original question "if the file extension is incorrect or missing". GetMimeMapping just uses a static dictionary of extension and mime entries.

I would advise editting your comment to note that this internally uses the file extension, which is easily faked.

c# - Using .NET, how can you find the mime type of a file based on the...

c# mime mime-types
Rectangle 27 43

If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.

var mimetype = System.Web.MimeMapping.GetMimeMapping(<pathToFile>);

This does not answer the original question "if the file extension is incorrect or missing". GetMimeMapping just uses a static dictionary of extension and mime entries.

I would advise editting your comment to note that this internally uses the file extension, which is easily faked.

c# - Using .NET, how can you find the mime type of a file based on the...

c# mime mime-types
Rectangle 27 10

JQuery just wraps the underlying File API used in most browsers, so there is no difference how JQuery and Javascript handle files and mime types. Here is the File API spec:

The File object that you are manipulating inherits the type property from the Blob object, and the browser uses the blob (byte array) to determine the mime type.

To accomplish that task each browser implements a file sniffing algorithm to "read" the mime type from the byte array, and if the mime type doesn't match, it will return an empty string like in your scenario above.

Here is the full algorithm spec:

So now you are wondering why it doesn't work for TAR, ZIP and RAR files, and why does it work for some people and not for you?.. because the file sniffing algorithm is evidently not perfect.

It uses byte pattern matching, and that seems not reliable enough.

For example i have used WinRaR on my windows 8 box to compress a file, and the initial bytes of the created file are:

52 61 72 21 1A 07 00

However, to recognize it as .RAR the browser byte pattern matching algorithm expects

52 61 72 20 1A 07 00

As you see there is a slight difference, and when i uploaded my RAR file to the browser using your code above, Firefox wasn't able to recognize the Mime-Type, and i got an empty string in the type property.

However, when i packed a ZIP file using WinRar on the same machine with default settings it generates an initial byte array sequence of 50 4B 03 04 that matched with the zip byte pattern expected by the algorithm, and when i used your code above it was able to detect the mime type correctly as application/zip!

So as you see from my explanation, it is a matter of serialization, and the "imperfection" of the algorithm that matches the serialized bytes with mime extensions in the browsers.

Based on everything mentioned above, i would recommend NOT relying on the mime sniffing, and instead use your custom code to determine the mime type OR existing libraries. You can use a server-side or a client-side approach.

If you want to stick to the client you could use the following JS library:

And then discovering the mime type would be a matter of one line of code:

mimetype.lookup("myfile.rar")

Just add if it was not clear: The "mimetype.js" is a simple lookup table. It works based on the extension of the file and search within a catalog the type corresponding.

Fantastic. This is exactly what I was looking for. The bounty is all yours (and is well deserved if I do say so myself).

javascript - Mime type missing for .rar and .tar - Stack Overflow

javascript jquery mime-types
Rectangle 27 6

You didn't state what web server you were using, but Apache has a nice little module called Mime Magic which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as Dave Webb Mentioned the MimeTypes Module under python will work, provided an extension is handy.

Alternatively, if you are sitting on a UNIX box you can use sys.popen('file -i ' + fileName, mode='r') to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is.

Nowdays you can just do subprocess.check_output(['file', '-b', '--mime', filename])

There is really no reason to resort to using an external tool when python-magic does the equivalent thing, all wrapped and cozy.

How to find the mime type of a file in python? - Stack Overflow

python mime
Rectangle 27 6

You didn't state what web server you were using, but Apache has a nice little module called Mime Magic which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as Dave Webb Mentioned the MimeTypes Module under python will work, provided an extension is handy.

Alternatively, if you are sitting on a UNIX box you can use sys.popen('file -i ' + fileName, mode='r') to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is.

Nowdays you can just do subprocess.check_output(['file', '-b', '--mime', filename])

There is really no reason to resort to using an external tool when python-magic does the equivalent thing, all wrapped and cozy.

How to find the mime type of a file in python? - Stack Overflow

python mime
Rectangle 27 6

It depends on where you are getting the input stream from. If you are getting it from a servlet then it is accessable through the HttpServerRequest object that is an argument of doPost. If you are using some sort of rest API like Jersey then the request can be injected by using @Context. If you are uploading the file through a socket it will be your responsibility to specify the MIME type as part of your protocol as you will not inherit the http headers.

java - How can I get MIME type of an InputStream of a file that is bei...

java servlets inputstream mime-types
Rectangle 27 2

@Steve Morgan and @Richard Gourlay this is a great solution, thank you for that. One small drawback is that when the number of bytes in a file is 255 or below, the mime type will sometimes yield "application/octet-stream", which is slightly inaccurate for files which would be expected to yield "text/plain". I have updated your original method to account for this situation as follows:

If the number of bytes in the file is less than or equal to 255 and the deduced mime type is "application/octet-stream", then create a new byte array that consists of the original file bytes repeated n-times until the total number of bytes is >= 256. Then re-check the mime-type on that new byte array.

Imports System.Runtime.InteropServices

<DllImport("urlmon.dll", CharSet:=CharSet.Auto)> _
Private Shared Function FindMimeFromData(pBC As System.UInt32, <MarshalAs(UnmanagedType.LPStr)> pwzUrl As System.String, <MarshalAs(UnmanagedType.LPArray)> pBuffer As Byte(), cbSize As System.UInt32, <MarshalAs(UnmanagedType.LPStr)> pwzMimeProposed As System.String, dwMimeFlags As System.UInt32, _
ByRef ppwzMimeOut As System.UInt32, dwReserverd As System.UInt32) As System.UInt32
End Function
Private Function GetMimeType(ByVal f As FileInfo) As String
    'See http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature
    Dim returnValue As String = ""
    Dim fileStream As FileStream = Nothing
    Dim fileStreamLength As Long = 0
    Dim fileStreamIsLessThanBByteSize As Boolean = False

    Const byteSize As Integer = 255
    Const bbyteSize As Integer = byteSize + 1

    Const ambiguousMimeType As String = "application/octet-stream"
    Const unknownMimeType As String = "unknown/unknown"

    Dim buffer As Byte() = New Byte(byteSize) {}
    Dim fnGetMimeTypeValue As New Func(Of Byte(), Integer, String)(
        Function(_buffer As Byte(), _bbyteSize As Integer) As String
            Dim _returnValue As String = ""
            Dim mimeType As UInt32 = 0
            FindMimeFromData(0, Nothing, _buffer, _bbyteSize, Nothing, 0, mimeType, 0)
            Dim mimeTypePtr As IntPtr = New IntPtr(mimeType)
            _returnValue = Marshal.PtrToStringUni(mimeTypePtr)
            Marshal.FreeCoTaskMem(mimeTypePtr)
            Return _returnValue
        End Function)

    If (f.Exists()) Then
        Try
            fileStream = New FileStream(f.FullName(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            fileStreamLength = fileStream.Length()

            If (fileStreamLength >= bbyteSize) Then
                fileStream.Read(buffer, 0, bbyteSize)
            Else
                fileStreamIsLessThanBByteSize = True
                fileStream.Read(buffer, 0, CInt(fileStreamLength))
            End If

            returnValue = fnGetMimeTypeValue(buffer, bbyteSize)

            If (returnValue.Equals(ambiguousMimeType, StringComparison.OrdinalIgnoreCase) AndAlso fileStreamIsLessThanBByteSize AndAlso fileStreamLength > 0) Then
                'Duplicate the stream content until the stream length is >= bbyteSize to get a more deterministic mime type analysis.
                Dim currentBuffer As Byte() = buffer.Take(fileStreamLength).ToArray()
                Dim repeatCount As Integer = Math.Floor((bbyteSize / fileStreamLength) + 1)
                Dim bBufferList As List(Of Byte) = New List(Of Byte)
                While (repeatCount > 0)
                    bBufferList.AddRange(currentBuffer)
                    repeatCount -= 1
                End While
                Dim bbuffer As Byte() = bBufferList.Take(bbyteSize).ToArray()
                returnValue = fnGetMimeTypeValue(bbuffer, bbyteSize)
            End If
        Catch ex As Exception
            returnValue = unknownMimeType
        Finally
            If (fileStream IsNot Nothing) Then fileStream.Close()
        End Try
    End If
    Return returnValue
End Function

This was the issue I had, and your idea was great, to copy the bytes. I had to implement it in c#, but using the length of the file, and the buffer that has the first bytes of the file, i was able to iterate over all missing bytes and copy the bytes in the array to repeat the file (i just copied the byte from the idx that was the file length earlier in the array).

c# - Using .NET, how can you find the mime type of a file based on the...

c# mime mime-types
Rectangle 27 2

@Steve Morgan and @Richard Gourlay this is a great solution, thank you for that. One small drawback is that when the number of bytes in a file is 255 or below, the mime type will sometimes yield "application/octet-stream", which is slightly inaccurate for files which would be expected to yield "text/plain". I have updated your original method to account for this situation as follows:

If the number of bytes in the file is less than or equal to 255 and the deduced mime type is "application/octet-stream", then create a new byte array that consists of the original file bytes repeated n-times until the total number of bytes is >= 256. Then re-check the mime-type on that new byte array.

Imports System.Runtime.InteropServices

<DllImport("urlmon.dll", CharSet:=CharSet.Auto)> _
Private Shared Function FindMimeFromData(pBC As System.UInt32, <MarshalAs(UnmanagedType.LPStr)> pwzUrl As System.String, <MarshalAs(UnmanagedType.LPArray)> pBuffer As Byte(), cbSize As System.UInt32, <MarshalAs(UnmanagedType.LPStr)> pwzMimeProposed As System.String, dwMimeFlags As System.UInt32, _
ByRef ppwzMimeOut As System.UInt32, dwReserverd As System.UInt32) As System.UInt32
End Function
Private Function GetMimeType(ByVal f As FileInfo) As String
    'See http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature
    Dim returnValue As String = ""
    Dim fileStream As FileStream = Nothing
    Dim fileStreamLength As Long = 0
    Dim fileStreamIsLessThanBByteSize As Boolean = False

    Const byteSize As Integer = 255
    Const bbyteSize As Integer = byteSize + 1

    Const ambiguousMimeType As String = "application/octet-stream"
    Const unknownMimeType As String = "unknown/unknown"

    Dim buffer As Byte() = New Byte(byteSize) {}
    Dim fnGetMimeTypeValue As New Func(Of Byte(), Integer, String)(
        Function(_buffer As Byte(), _bbyteSize As Integer) As String
            Dim _returnValue As String = ""
            Dim mimeType As UInt32 = 0
            FindMimeFromData(0, Nothing, _buffer, _bbyteSize, Nothing, 0, mimeType, 0)
            Dim mimeTypePtr As IntPtr = New IntPtr(mimeType)
            _returnValue = Marshal.PtrToStringUni(mimeTypePtr)
            Marshal.FreeCoTaskMem(mimeTypePtr)
            Return _returnValue
        End Function)

    If (f.Exists()) Then
        Try
            fileStream = New FileStream(f.FullName(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            fileStreamLength = fileStream.Length()

            If (fileStreamLength >= bbyteSize) Then
                fileStream.Read(buffer, 0, bbyteSize)
            Else
                fileStreamIsLessThanBByteSize = True
                fileStream.Read(buffer, 0, CInt(fileStreamLength))
            End If

            returnValue = fnGetMimeTypeValue(buffer, bbyteSize)

            If (returnValue.Equals(ambiguousMimeType, StringComparison.OrdinalIgnoreCase) AndAlso fileStreamIsLessThanBByteSize AndAlso fileStreamLength > 0) Then
                'Duplicate the stream content until the stream length is >= bbyteSize to get a more deterministic mime type analysis.
                Dim currentBuffer As Byte() = buffer.Take(fileStreamLength).ToArray()
                Dim repeatCount As Integer = Math.Floor((bbyteSize / fileStreamLength) + 1)
                Dim bBufferList As List(Of Byte) = New List(Of Byte)
                While (repeatCount > 0)
                    bBufferList.AddRange(currentBuffer)
                    repeatCount -= 1
                End While
                Dim bbuffer As Byte() = bBufferList.Take(bbyteSize).ToArray()
                returnValue = fnGetMimeTypeValue(bbuffer, bbyteSize)
            End If
        Catch ex As Exception
            returnValue = unknownMimeType
        Finally
            If (fileStream IsNot Nothing) Then fileStream.Close()
        End Try
    End If
    Return returnValue
End Function

This was the issue I had, and your idea was great, to copy the bytes. I had to implement it in c#, but using the length of the file, and the buffer that has the first bytes of the file, i was able to iterate over all missing bytes and copy the bytes in the array to repeat the file (i just copied the byte from the idx that was the file length earlier in the array).

c# - Using .NET, how can you find the mime type of a file based on the...

c# mime mime-types
Rectangle 27 79

Are you using .NET 3.5? You could use the ZipPackage class and related classes. Its more than just zipping up a file list because it wants a MIME type for each file you add. It might do what you want.

I'm currently using these classes for a similar problem to archive several related files into a single file for download. We use a file extension to associate the download file with our desktop app. One small problem we ran into was that its not possible to just use a third-party tool like 7-zip to create the zip files because the client side code can't open it -- ZipPackage adds a hidden file describing the content type of each component file and cannot open a zip file if that content type file is missing.

This has worked well in the past for me.

Oh SO, how I love you! Thanks Brian; yuo just saved us a lot of headaches and some $$$.

Note that this doesn't always work in reverse. Some Zip files will not rehydrate using the ZipPackage class. Files made with ZipPackage will so you should be good.

(Answer to the above "sigh": Open "References" and add (illogically enough) "WindowsBase".)

compression - How do I ZIP a file in C#, using no 3rd-party APIs? - St...

c# compression zip download
Rectangle 27 79

Are you using .NET 3.5? You could use the ZipPackage class and related classes. Its more than just zipping up a file list because it wants a MIME type for each file you add. It might do what you want.

I'm currently using these classes for a similar problem to archive several related files into a single file for download. We use a file extension to associate the download file with our desktop app. One small problem we ran into was that its not possible to just use a third-party tool like 7-zip to create the zip files because the client side code can't open it -- ZipPackage adds a hidden file describing the content type of each component file and cannot open a zip file if that content type file is missing.

This has worked well in the past for me.

Oh SO, how I love you! Thanks Brian; yuo just saved us a lot of headaches and some $$$.

Note that this doesn't always work in reverse. Some Zip files will not rehydrate using the ZipPackage class. Files made with ZipPackage will so you should be good.

(Answer to the above "sigh": Open "References" and add (illogically enough) "WindowsBase".)

compression - How do I ZIP a file in C#, using no 3rd-party APIs? - St...

c# compression zip download
Rectangle 27 84

Create a form, use the POST method, submit the form - there's no need for an iframe. When the server page responds to the request, write a response header for the mime type of the file, and it will present a download dialog - I've done this a number of times.

You want content-type of application/download - just search for how to provide a download for whatever language you're using.

As stated in the question: "Using a plain HTML form is also not an option."

No, because using a regular POST would navigate the browser to the POST URL. I don't want to navigate away from the page. I want to perform the request in the background, process the response and present it to the client.

If the server sends back headers like the other answer has, it opens in a new window - I've done it before. It would only navigate away if your server-side script returned HTML code

@PavlePredic did you end up figuring out how to manage both response scenarios, i.e. JSON text response or download file response?

Answer is not clear and the proposed solution doesn't work.

javascript - Handle file download from ajax post - Stack Overflow

javascript jquery ajax
Rectangle 27 15

You can check the MIME type of the file using PHP's File Info Functions. If it returns with the type 'application/pdf' then it should be a PDF.

The File Info Functions were added in PHP 5.3 but previous to that you are able to use the mime_content_type function (depreciated in 5.3)

but if i have a php file and write(header: type="application/pdf")...than it will also show me the same

That's true, but that is less likely and it depends how critical this is

+1 that's only correct answer here. file info function provide a way to get true* mime type of the file

i don't want the mime type...i want to check the content of the file and check that is it php or not.?

php - how to check the uploaded file type is pdf - Stack Overflow

php html pdf
Rectangle 27 14

You can check the MIME type of the file using PHP's File Info Functions. If it returns with the type 'application/pdf' then it should be a PDF.

The File Info Functions were added in PHP 5.3 but previous to that you are able to use the mime_content_type function (depreciated in 5.3)

but if i have a php file and write(header: type="application/pdf")...than it will also show me the same

That's true, but that is less likely and it depends how critical this is

+1 that's only correct answer here. file info function provide a way to get true* mime type of the file

It should be noted that (as mentioned elsewhere on SO) the mime_content_type() function has not been deprecated, and is explicitly mentioned as included in PHP7.

php - how to check the uploaded file type is pdf - Stack Overflow

php html pdf
Rectangle 27 15

The web server is probably serving the image using the image/x-png MIME type. Chrome does not recognise this as an image (as of August 2012 February 2013), hence offers the file as a download.

image/x-png is a legacy MIME type from the days before it got its official name, image/png, in 1996. However, when Internet Explorer uploads an image it does so using image/x-png "for backward compatibility". I believe this was the case up to IE8, and was "fixed" in IE9. If the web server does not correctly handle this (the web server should detect this non-standard MIME type and treat it as image/png), then it may serve up the client-provided MIME type to other users, including to Google Chrome. Additionally, some web sites will serve up all PNGs as image/x-png.

If you're the web developer

image-png
image/x-png

If you're the user

Ok. So this explains the problem. But where's the solution?

file io - Chrome downloads PNG image links. I want them to open for vi...

google-chrome file-io png mime-types