验证上传文件格式问题

验证时需要根据文件编码进行验证(如果只根据后缀名验证是肤浅的):

package class3;

/**
 * 文件类型枚举类
 * 
 * @author guoy
 *
 */
public enum FileType {
	JPEG("FFD8FF"), PNG("89504E47"), GIF("47494638"), TIFF("49492A00"), BMP("424D"), DWG("41433130"), PSD(
			"38425053"), XML("3C3F786D6C"), HTML("68746D6C3E"), PDF(
					"255044462D312E"), ZIP("504B0304"), RAR("52617221"), WAV("57415645"), AVI("41564920");

	private String value = "";

	private FileType(String value) {
		this.value = value;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
}

package class3;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.util.StringUtils;

public class CheckUploadFile {

	public static void main(String[] args) throws IOException {

		String filePath = "C:\\Users\\guoy\\Desktop\\CgEOA1b87iCAD5rPAIxP9HuPBic206.jpg";
		System.out.println(getFileHeader(filePath));
		FileType type = getType(filePath);
		System.out.println(type.getValue());

		boolean check = checkFileType(filePath);
		System.out.println(check);
	}

	/**
	 * 判断文件类型是否合法
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static boolean checkFileType(String filePath) throws IOException {
		FileType type = getType(filePath);
		if (type == null || type.getValue() == null || type.getValue().length() == 0) {
			return false;
		}
		return true;
	}

	/**
	 * 判断文件类型
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static FileType getType(String filePath) throws IOException {
		String fileHead = getFileHeader(filePath);
		if (StringUtils.isEmpty(fileHead)) {
			return null;
		}
		fileHead = fileHead.toUpperCase();
		FileType[] fileTypes = FileType.values();
		for (FileType fileType : fileTypes) {
			if (fileHead.startsWith(fileType.getValue())) {
				return fileType;
			}
		}
		return null;
	}

	/**
	 * 读取文件头
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	private static String getFileHeader(String filePath) throws IOException {
		byte[] b = new byte[28];
		InputStream inputStream = new FileInputStream(filePath);
		inputStream.read(b, 0, 28);
		inputStream.close();
		return bytes2Hex(b);
	}

	/**
	 * byte数组转hex字符串<br/>
	 * 一个byte转为2个hex字符
	 * 
	 * @param src
	 * @return
	 */
	public static String bytes2Hex(byte[] src) {
		char[] res = new char[src.length * 2];
		final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		for (int i = 0, j = 0; i < src.length; i++) {
			res[j++] = hexDigits[src[i] >>> 4 & 0x0f];
			res[j++] = hexDigits[src[i] & 0x0f];
		}
		return new String(res);
	}
}


你可能感兴趣的:(验证上传文件格式问题)