1. 문제 설명
프로젝트 개발 중에는 종종 이미지의 형식 인 파일 업로드 문제가 발생합니다. 대부분의 경우 많은 사람들이 아래와 같이 접미사 이름을 사용하여 판단합니다.
if (filename.endswith ( ". png") || filename.endswith ( ". jpg")) {// 그림 저장} else {new ioException ( "Error File Format!");}그러나이 방법은 상당히 신뢰할 수 없습니다. Zip 파일, rmvb 파일, CSS, JS를 업로드하여 접미사 이름 JPG 또는 PNG를 수정하거나 서버에 업로드하여 서버에 더러운 데이터가 나타납니다. 또한 일부 이미지 파일의 경우 잘못된 확장자로 수정되면 일부 브라우저가 이미지를 표시하지 못할 수 있습니다.
2. 솔루션
컴퓨터 시스템에서 미디어 유형 파일에는 [식별자]가 있고 Zip과 그림 자체는 미디어 파일에 속하므로 인코딩 및 디코딩을 통해 사진이 합법적인지 여부를 결정할 수 있습니다.
1. 판단 및 표시 방법
개인 정적 부울 ISBMP (byte [] buf) {byte [] markbuf = "bm".getBytes (); // BMP 이미지 파일의 첫 두 바이트 반환 비교 (Buf, Markbuf); } private static boolean isicon (byte [] buf) {byte [] markbuf = {0, 0, 1, 0, 1, 0, 32, 32}; 반환 비교 (Buf, Markbuf); } private static boolean iswebp (byte [] buf) {byte [] markbuf = "riff".getBytes (); // Webp Image Identifier Return Compar (Buf, Markbuf); } private static boolean isgif (byte [] buf) {byte [] markbuf = "gif89a".getBytes (); // gif identifier if (compare (buf, markbuf)) {return true; } markbuf = "gif87a".getBytes (); // gif identifier if (compare (buf, markbuf)) {return true; } false를 반환합니다. } private static boolean ispng (byte [] buf) {byte [] markbuf = {(byte) 0x89,0x50,0x4e, 0x47,0x0d, 0x0a, 0x1a, 0x0a}; // png 식별자 // new String (buf) .indexof ( "png")> 0 //이 메소드는 비교 (Buf, Markbuf)를 반환하는 데 사용될 수 있습니다. } private static boolean isjpegheader (byte [] buf) {byte [] markbuf = {(byte) 0xff, (byte) 0xd8}; // jpeg start 문자 리턴 비교 (Buf, Markbuf); } private static boolean isjpegfooter (byte [] buf) // jpeg 결말 문자 {byte [] markbuf = {(byte) 0xff, (byte) 0xd9}; 반환 비교 (Buf, Markbuf); }2. 핵심 방법
/ ** * 파일의 mimeType을 가져옵니다 * @param filename * @return */ private static string getMimeType (String filename) {try {String Mimetype = readType (filename); return string.format ( "image/%s", mimetype); } catch (ioexception e) {e.printstacktrace (); } return null; } / ** * 파일 읽기 * @param filename * @return * @throws ioexception * / private static string readtype (String filename)는 ioexception {fileInputStream fis = null; try {file f = 새 파일 (filename); if (! f.exists () || f.isdirectory () || f.length () <8) {Throw new ioException ( "파일 [" "+f.getabsolutepath ()+"]는 이미지가 아닙니다! "); } fis = 새로운 fileInputStream (f); 바이트 [] bufheaders = readInputStreamat (fis, 0,8); if (isjpegheader (bufheaders)) {long skiplength = f.length () -2-8; // 처음 8 바이트를 읽으면 바이트를 빼야합니다 [] Buffooters = readInputStreamat (fis, skiplength, 2); if (isjpegfooter (buffooters)) {return "jpeg"; }} if (ispng (bufheaders)) {return "png"; } if (isgif (bufheaders)) {return "gif"; } if (iswebp (bufheaders)) {return "webp"; } if (isbmp (bufheaders)) {return "bmp"; } if (isicon (bufheaders)) {return "ico"; } 새로운 ioException을 던지십시오 ( "이미지의 형식은 무너졌습니다!"); } catch (filenotfoundException e) {Throw e; } 마침내 {try {if (fis! = null) fis.close (); } catch (예외 e) {}}} / *** 표시 일관성 비교* @param buf mark가 감지 될* @param markbuf 식별자 식별자 배열* @return 거짓 마크 부호 불일치* / private static boolean 비교 (byte [] buf, byte [] markbuf) {<int i = 0; i <markbuf.length. Markbuf [i]; 바이트 a = buf [i]; if (a! = b) {return false; }} true를 반환합니다. } / **** @param fis 입력 스트림 객체* @param skiplength skip position length 길이* @param 길이* @return byte array* @throws ioexception* / private static byte [] readInputStreamat (pileInputStream fis, long skiplength, int length) {byte [] bute [] byte [byte [new byte]; fis.skip (skiplength); // int read = fis.read (buf, 0, length); 반환 buf; }3. 테스트 코드
정상 테스트
public class imageType {public static void main (String [] args) {String filename = "oschina.jpg"; 문자열 유형 = getMimeType (filename); System.out.println (유형); }} 산출
이미지/jpeg
확장 테스트를 수정하십시오
Oschina.jpeg를 Oschina.png로 수정하십시오
copy oschina.png 확장을 삭제합니다
public class imageType {public static void main (string [] args) {String filename = "oschina.png"; 문자열 유형 = getMimeType (filename); System.out.println (유형); filename = "Oschina"; type = getMimeType (filename); System.out.println (유형); }} 산출
이미지/jpeg
이미지/jpeg
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.