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

验证上传文件的文件头判断是否为图片

程序员文章站 2024-02-19 19:33:22
...
项目中需要上传图片的功能,只判断文件后缀则修改文件后缀为图片格式的非图片文件也能通过验证,下面的代码能判断文件头是否为图片,如果返回null则非图片文件。
public static void main(String[] args) {
File f = new File("c://test.PNG");
if (f.exists()) {
System.out.println(getFormatName(f));
}
}

// Returns the format name of the image in the object 'o'.
// Returns null if the format is not known.
private static String getFormatName(Object o) {
try {
// Create an image input stream on the image
ImageInputStream iis = ImageIO.createImageInputStream(o);

// Find all image readers that recognize the image format
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
// No readers found
return null;
}

// Use the first reader
ImageReader reader = iter.next();

// Close stream
iis.close();

// Return the format name
return reader.getFormatName();
} catch (IOException e) {
e.printStackTrace();
}

// The image could not be read
return null;
}

这段代码还是不能满足要求,因为必须传入File为参数,但是struts上传FormFile无法直接获取本地File的路径,会报空指针异常。
又查了些资料,下面的代码能判断上传的FormFile是否后缀为图片格式,但是经过我测试修改其他文件的后缀为图片格式是无法判断的
public boolean isImage(FormFile formFile) {

List<String> allowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpg","image/jpeg","image/pjpeg");
return allowType.contains(formFile.getContentType());

}



之前发的这篇文章给斑竹挪动到问答频道了。。。。再写出来 :x

综合了大家的意见其实没必要在服务器端进行如此麻烦的操作,必须用io流检查文件头才能验明真身