如何判断上传的图片是否是正真的图片 防止上传恶意的非图片文件

		final String JPG = "ffd8ffe0";//魔幻数字
		final char[] HEX = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
		InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("1.jpg");
		int len = JPG.length()/2 + JPG.length()%2;
		byte[] bs = new byte[len];
		if( in.read(bs) == len ){
			StringBuilder sb = new StringBuilder();
			for(byte i=0;i>>4&0xF;
				int low  = bs[i]&0xF;
				sb.append(HEX[high]).append(HEX[low]);
			}
			System.out.println(JPG.startsWith(JPG));
		}
		in.close();

 

几种常规图片格式的“魔幻数字”
File type Typical extension Hex digits xx = variable
Bitmap format .bmp 42 4d
GIF format .gif 47 49 46 38
JPEG File Interchange Format .jpg ff d8 ff e0
PNG format .png 89 50 4e 47

你可能感兴趣的:(java编程)