mitao
2025-02-21 31573d6180d15ef65ed0df9c2732495f40b12663
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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);
//     }
}