PHP JAVA C上传文件如何准确判断文件类型-mime知识普及

MIME的英文全称是"Multipurpose Internet Mail Extensions" 多功能Internet 邮件扩充服务,它是一种多用途网际邮件扩充协议,在1992年最早应用于电子邮件系统,但后来也应用到浏览器。服务器会将它们发送的多媒体数据的类型告诉 浏览器,而通知手段就是说明该多媒体数据的MIME类型,从而让浏览器知道接收到的信息哪些是MP3文件,哪些是Shockwave文件等等。服务器将 MIME标志符放入传送的数据中来告诉浏览器使用哪种插件读取相关文件。

文件 用IE7上传 用Firefox3.0上传
GIF

image/gif

image/gif

JPG

image/pjpeg

image/jpeg

ZIP application/x-compressed application/octet-stream
JSP

text/html

text/html

EXE application/octet-stream application/octet-stream
上边的图哦不红图表示出了不同的浏览器所上传的不同的mime的区别,研究了一下,暂时没有发现可修改假冒mime的方法。

<form enctype="multipart/form-data" action="URL" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="1000"> <input name="myFile" type="file"> <input type="submit" value="上传文件"> </form>

这个代码上传文件后:

使用PHP:

$_FILES['myFile']['type']   文件的 MIME 类型,需要浏览器提供该信息的支持,例如"image/gif"。

使用struts2限制类型:

<interceptor-ref name="fileUpload">
<param name="allowedTypes">application/zip,application/x-zip-compressed,application/rar,application/octet-stream</param>
<param name="maximumSize">3145728</param>
</interceptor-ref>

使用C/java(由人人网文斌大侠提供):

public static boolean isImageJpeg(byte[] blob) {

       if (blob != null && blob.length > 2) {

           // 0xFFD8

           if (blob[0] == (byte)0xFF &&

              blob[1] == (byte)0xD8) {

              return true;

           }

       }

       return false;

    }

    public static boolean isImageBmp(byte[] blob) {

       if (blob != null && blob.length > 2) {

           // BM: Windows 3.1x, 95, NT, …

           // BA: OS/2 Bitmap Array

           // CI: OS/2 Color Icon

           // CP: OS/2 Color Pointer

           // IC: OS/2 Icon

           // PT: OS/2 Pointer

           if ((blob[0] == 'B' &&

               blob[1] == 'M')

               ||

              (blob[0] == 'B' &&

               blob[1] == 'A')) {

              return true;

           }

       }

       return false;

    }

    public static boolean isImagePng(byte[] blob) {

       if (blob != null && blob.length > 8) {

           // 89 50 4E 47 0D 0A 1A 0A

           if (blob[0] == (byte)0x89 &&

              blob[1] == (byte)0x50 &&

              blob[2] == (byte)0x4E &&

              blob[3] == (byte)0x47    &&

              blob[4] == (byte)0x0D &&

              blob[5] == (byte)0x0A &&

              blob[6] == (byte)0x1A &&

              blob[7] == (byte)0x0A)

              return true;

       }

       return false;

    }

    public static boolean isImageGif(byte[] blob) {

       if (blob != null && blob.length > 3) { // 只有3字节的gif?这里仅避免异常

           if (blob[0] == 'G' &&

              blob[1] == 'I' &&

              blob[2] == 'F')

              return true;

       }

       return false;

    }


原创文章如转载,请注明:转载自五四陈科学院[http://www.54chen.com]

捐款订阅54chen
捐赠说明