欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2021-02-02

程序员文章站 2022-03-10 21:56:02
...

判断上传图片的类型。这里只判断了图片的类型。根据需求自己修改,

 // @Jurisdiction
   // @RootAndClass("ImageUp")
    @PostMapping("/ImageUp")
    public Object ImageUp(@RequestParam("Image") MultipartFile me,HttpServletRequest request) {

        String path =request.getSession().getServletContext().getRealPath("");
        System.out.println(path);
        if(me.isEmpty()){
              return ResponseDataUtil.buildError("请上传图片");
        }else {
            try {
                FileInputStream is = (FileInputStream) me.getInputStream();
                if(!ImageController.IsBooleanImage(is)){
                    System.out.println("该文件不符合图片类型");
                }
              
            }catch (Exception e){
                System.out.println(e);
                return  e;
            }
        }

        return ResponseDataUtil.buildError("上传成功");
    }
 //判断是否是图片
    public static boolean IsBooleanImage(FileInputStream is) throws IOException {

       // FileInputStream is = new FileInputStream("F:\\aaa.jpg");
        byte[] b = new byte[3];
        is.read(b, 0, b.length);
        String photo = bytesToHexString(b);
        System.out.println("photo :"+photo);
        boolean ooo = ImageController.checkType(photo);
        System.out.println("后缀名是:" + ooo);
        return  ooo;
    }

    public 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.toUpperCase());  //小写转大写
        }
        return stringBuilder.toString();
    }

    public static boolean checkType(String fileType) {

        switch (fileType) {
            case "FFD8FF": return true;  //jpg
            case "89504E": return true;  //png
            case "474946": return true;  //jif
            default: return false;
        }
    }