package com.panzhihua.common.utlis;
|
|
import java.io.FileInputStream;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
/**
|
* FileType 应用模块名称
|
* <p>
|
* 代码描述 文件类型判断工具类
|
* <p>
|
* Copyright: Copyright (C) 2021 XXX, Inc. All rights reserved.
|
* <p>
|
* Company: 成都呐喊信息技术有限公司
|
* <p>
|
*
|
* @author manailin
|
* @since 2021/10/8 10:52
|
*/
|
@Slf4j
|
public class FileType {
|
|
private static final String NOT_IMAGE_FILE_TYPE = "0000";
|
|
private static String bytesToHexString(byte[] src) {
|
StringBuilder stringBuilder = new StringBuilder();
|
if (src == null || src.length <= 0) {
|
return null;
|
}
|
for (int i = 0; i < src.length; i++) {
|
int v = src[i] & 0xFF;
|
String hv = Integer.toHexString(v);
|
if (hv.length() < 2) {
|
stringBuilder.append(0);
|
}
|
stringBuilder.append(hv);
|
}
|
return stringBuilder.toString();
|
}
|
|
/**
|
* [方法描述] 判断上传的文件是否是规定的文件文件,通过文件头标识确定
|
*
|
* @param is
|
* @return boolean
|
* @author manailin
|
* @date 2021/10/28 16:50
|
*/
|
public static Boolean checkFileType(FileInputStream is) throws Exception {
|
byte[] b = new byte[3];
|
is.read(b, 0, b.length);
|
String photo = bytesToHexString(b);
|
photo = photo.toUpperCase();
|
String fileHeadCode = TypeDict.checkFileType(photo);
|
log.info("上传的文件类型{}", fileHeadCode);
|
return !fileHeadCode.equals(NOT_IMAGE_FILE_TYPE);
|
}
|
|
/**
|
* [方法描述] 判断上传的文件是否是图片文件,通过文件头标识确定
|
*
|
* @param is
|
* @return boolean
|
* @author manailin
|
* @date 2021/10/28 16:50
|
*/
|
public static Boolean checkImageType(FileInputStream is) throws Exception {
|
byte[] b = new byte[3];
|
is.read(b, 0, b.length);
|
String photo = bytesToHexString(b);
|
photo = photo.toUpperCase();
|
String fileHeadCode = TypeDict.checkImageType(photo);
|
log.info("上传的文件类型{}", fileHeadCode);
|
return !fileHeadCode.equals(NOT_IMAGE_FILE_TYPE);
|
}
|
/**
|
* [方法描述] 方法参照流程
|
*
|
* @param args
|
*/
|
// public static void main(String[] args) throws Exception {
|
// FileInputStream is = new FileInputStream("D:\\Pictures\\3.mp4");
|
// byte[] b = new byte[3];
|
// is.read(b, 0, b.length);
|
// String photo = bytesToHexString(b);
|
// photo = photo.toUpperCase();
|
// System.out.println("头文件是:" + photo);
|
// String ooo = TypeDict.checkFileType(photo);
|
// System.out.println("后缀名是:" + ooo);
|
// }
|
}
|