在我的网络应用程序中,我有一个图像上传模块。我想检查上传的文件是图像文件还是任何其他文件。我在服务器端使用 Java。
像BufferedImage
在 java 中一样读取图像,然后我将其写入磁盘ImageIO.write()
我该如何检查BufferedImage
,它是否真的是图像或其他东西?
任何建议或链接将不胜感激。
在我的网络应用程序中,我有一个图像上传模块。我想检查上传的文件是图像文件还是任何其他文件。我在服务器端使用 Java。
像BufferedImage
在 java 中一样读取图像,然后我将其写入磁盘ImageIO.write()
我该如何检查BufferedImage
,它是否真的是图像或其他东西?
任何建议或链接将不胜感激。
我假设您在 servlet 上下文中运行它。如果仅根据文件扩展名检查内容类型是负担得起的,则使用ServletContext#getMimeType()
获取 mime 类型(内容类型)。只需检查它是否以image/
.
String fileName = uploadedFile.getFileName();
String mimeType = getServletContext().getMimeType(fileName);
if (mimeType.startsWith("image/")) {
// It's an image.
}
默认的 mime 类型在相关web.xml
的 servletcontainer 中定义。例如在 Tomcat 中,它位于/conf/web.xml
. 您可以在 webapp 中扩展/覆盖它,/WEB-INF/web.xml
如下所示:
<mime-mapping>
<extension>svg</extension>
<mime-type>image/svg+xml</mime-type>
</mime-mapping>
但这并不能阻止您通过更改文件扩展名来欺骗您的用户。如果您也想涵盖这一点,那么您还可以根据实际文件内容确定 mime 类型。如果只检查 BMP、GIF、JPG 或 PNG 类型(而不是 TIF、PSD、SVG 等)是负担得起的,那么您可以直接将其输入ImageIO#read()
并检查它是否不会引发异常。
try (InputStream input = uploadedFile.getInputStream()) {
try {
ImageIO.read(input).toString();
// It's an image (only BMP, GIF, JPG and PNG are recognized).
} catch (Exception e) {
// It's not an image.
}
}
但是,如果您还想涵盖更多图像类型,请考虑使用 3rd 方库,该库通过嗅探文件头来完成所有工作。例如支持 BMP、GIF、JPG、PNG、TIF 和 PSD(但不支持 SVG)的JMimeMagic或Apache Tika 。Apache Batik支持 SVG。下面的示例使用 JMimeMagic:
try (InputStream input = uploadedFile.getInputStream()) {
String mimeType = Magic.getMagicMatch(input, false).getMimeType();
if (mimeType.startsWith("image/")) {
// It's an image.
} else {
// It's not an image.
}
}
如有必要,您可以使用组合并超过一个和另一个。
也就是说,您不一定需要ImageIO#write()
将上传的图像保存到磁盘。只需将获得的InputStream
直接写入Path
或任何OutputStream
类似FileOutputStream
通常的 Java IO 方式就足够了(另请参阅在 servlet 应用程序中保存上传文件的推荐方式):
try (InputStream input = uploadedFile.getInputStream()) {
Files.copy(input, new File(uploadFolder, fileName).toPath());
}
除非你想收集一些图像信息,比如它的尺寸和/或想要操纵它(裁剪/调整大小/旋转/转换/等)。
在我的案例中,我使用了org.apache.commons.imaging.Imaging。以下是检查图像是否为 jpeg 图像的示例代码。如果上传的文件不是图像,它会抛出 ImageReadException。
try {
//image is InputStream
byte[] byteArray = IOUtils.toByteArray(image);
ImageFormat mimeType = Imaging.guessFormat(byteArray);
if (mimeType == ImageFormats.JPEG) {
return;
} else {
// handle image of different format. Ex: PNG
}
} catch (ImageReadException e) {
//not an image
}
这是内置在 JDK 中的,只需要一个支持
byte[] data = ;
InputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
String mimeType = URLConnection.guessContentTypeFromStream(is);
//...close stream
尝试使用多部分文件而不是BufferedImage
import org.apache.http.entity.ContentType;
...
public void processImage(MultipartFile file) {
if(!Arrays.asList(ContentType.IMAGE_JPEG.getMimeType(), ContentType.IMAGE_PNG.getMimeType(), ContentType.IMAGE_GIF.getMimeType()).contains(file.getContentType())) {
throw new IllegalStateException("File must be an Image");
}
}