目录

大橙子

VX:ZzzChChen
Phone:13403656751
Email:zxydczzs@gmail.com

Java判断文件是否为图片类型且MultipartFile转File

 1        private MimetypesFileTypeMap mtftp;
 2
 3        mtftp = new MimetypesFileTypeMap();
 4        mtftp.addMimeTypes("image png tif jpg jpeg bmp");
 5        String contentType;
 6        try {
 7            contentType = mtftp.getContentType(multipartFileToFile(multipartFile));
 8        } catch (IOException e) {
 9            e.printStackTrace();
10        }
11        String type = contentType.split("/")[0];
12        if(!"image".equals(type)){
13            //非图片类型
14        }
15
16    /**
17     * MultipartFile 转 File
18     *
19     * @param file
20     * @throws Exception
21     */
22    public File multipartFileToFile(MultipartFile file) throws IOException {
23
24        File toFile = null;
25        if (file.equals("") || file.getSize() <= 0) {
26            file = null;
27        } else {
28            InputStream ins = null;
29            ins = file.getInputStream();
30            toFile = new File(file.getOriginalFilename());
31            inputStreamToFile(ins, toFile);
32            ins.close();
33        }
34        return toFile;
35    }
36    //获取流文件
37    private void inputStreamToFile(InputStream ins, File file) {
38        try {
39            OutputStream os = new FileOutputStream(file);
40            int bytesRead = 0;
41            byte[] buffer = new byte[8192];
42            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
43                os.write(buffer, 0, bytesRead);
44            }
45            os.close();
46            ins.close();
47        } catch (Exception e) {
48            e.printStackTrace();
49        }
50    }

标题:Java判断文件是否为图片类型且MultipartFile转File
作者:zzzzchen
地址:https://dczzs.com/articles/2021/06/28/1624872721673.html