如何检查上传的文件是图片还是其他文件? [英] How to check a uploaded file whether it is an image or other file?

查看:21
本文介绍了如何检查上传的文件是图片还是其他文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网络应用程序中,我有一个图像上传模块.我想检查上传的文件是图像文件还是任何其他文件.我在服务器端使用 Java.

In my web application I have an image uploading module. I want to check the uploaded file whether it's an image file or any other file. I am using Java in server side.

图像在java中被读取为BufferedImage,然后我用ImageIO.write()

The image is read as BufferedImage in java and then I am writing it to disk with ImageIO.write()

我应该如何检查BufferedImage,它是真的图像还是其他东西?

How shall I check the BufferedImage, whether it's really an image or something else?

任何建议或链接将不胜感激.

Any suggestions or links would be appreciated.

推荐答案

我假设您在 servlet 上下文中运行它.如果仅根据文件扩展名检查内容类型是负担得起的,那么使用 ServletContext#getMimeType() 获取 MIME 类型(内容类型).只需检查它是否以 image/ 开头.

I'm assuming that you're running this in a servlet context. If it's affordable to check the content type based on just the file extension, then use ServletContext#getMimeType() to get the mime type (content type). Just check if it starts with image/.

String fileName = uploadedFile.getFileName();
String mimeType = getServletContext().getMimeType(fileName);
if (mimeType.startsWith("image/")) {
    // It's an image.
}

默认 MIME 类型在相关 servlet 容器的 web.xml 中定义.例如,在 Tomcat 中,它位于 /conf/web.xml 中.您可以在您的 web 应用程序的 /WEB-INF/web.xml 中扩展/覆盖它,如下所示:

The default mime types are definied in the web.xml of the servletcontainer in question. In for example Tomcat, it's located in /conf/web.xml. You can extend/override it in the /WEB-INF/web.xml of your webapp as follows:

<mime-mapping>
    <extension>svg</extension>
    <mime-type>image/svg+xml</mime-type>
</mime-mapping>

但这并不能阻止用户通过更改文件扩展名来欺骗您.如果您也想涵盖这一点,那么您还可以根据实际文件内容确定 MIME 类型.如果仅检查 BMP、GIF、JPG 或 PNG 类型(而不是 TIF、PSD、SVG 等)可以负担得起,那么您可以直接将其提供给 ImageIO#read() 并检查如果不抛出异常.

But this doesn't prevent you from users who are fooling you by changing the file extension. If you'd like to cover this as well, then you can also determine the mime type based on the actual file content. If it's affordable to check for only BMP, GIF, JPG or PNG types (but not TIF, PSD, SVG, etc), then you can just feed it directly to ImageIO#read() and check if it doesn't throw an exception.

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.
    }
}

但是,如果您还想涵盖更多图像类型,请考虑使用第 3 方库,该库通过嗅探 文件头.例如 JMimeMagicApache Tika 支持 BMP、GIF、JPG、PNG、TIF 和 PSD(但不支持 SVG).Apache Batik 支持 SVG.下面的示例使用 JMimeMagic:

But if you'd like to cover more image types as well, then consider using a 3rd party library which does all the work by sniffing the file headers. For example JMimeMagic or Apache Tika which support both BMP, GIF, JPG, PNG, TIF and PSD (but not SVG). Apache Batik supports SVG. Below example uses 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.
    }
}

如有必要,您可以使用组合并权衡两者.

You could if necessary use combinations and outweigh the one and other.

也就是说,您不一定需要 ImageIO#write() 将上传的图像保存到磁盘.只需将获得的 InputStream 直接写入 Path 或任何 OutputStreamFileOutputStream 通常的 Java IO 方式足够(另请参阅将上传的文件保存在servlet 应用程序):

That said, you don't necessarily need ImageIO#write() to save the uploaded image to disk. Just writing the obtained InputStream directly to a Path or any OutputStream like FileOutputStream the usual Java IO way is more than sufficient (see also Recommended way to save uploaded files in a servlet application):

try (InputStream input = uploadedFile.getInputStream()) {
    Files.copy(input, new File(uploadFolder, fileName).toPath());
}

当然,除非您想收集一些图像信息,例如其尺寸和/或想要对其进行操作(裁剪/调整大小/旋转/转换等).

Unless you'd like to gather some image information like its dimensions and/or want to manipulate it (crop/resize/rotate/convert/etc) of course.

这篇关于如何检查上传的文件是图片还是其他文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆