Java/ImageIO 在读取整个文件之前验证格式?
我正在开发一个允许用户上传图像的 Web 应用程序。 我担心的是文件的大小,特别是如果它们是无效的格式。
我想知道java(或第三方库)中是否有一种方法可以在读取整个文件之前检查允许的文件格式(jpg、gif 和 png)。
I'm developing a Web application that will let users upload images.
My concern is the file´s size, specially if they are invalid formats.
I'm wondering if there´s a way in java (or a third party library) to check the allowed files formats (jpg, gif and png) before reading the entire file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只想支持几种类型的图像,您可以从(上传)加载图像开始,并在某个时候使用前几个字节来检查您是否希望继续上传。
相当多的图像格式可以通过前几个字节来识别,
查看 此页面 查看一些检查 mime 类型的 Java 。请阅读文档或源代码以检查任何给定方法是否需要整个文件,或者可以对前几个字节进行操作。我没有使用过这些库:)
另请查看 此页面 其中还列出了一些java库,以及一些检测所依据的论文。
如果您找到了自己喜欢的东西,请不要忘记提供一些反馈!
If you wish to support only a few types of images you can start by (up)loading the image and at some point use the first few bytes to check wether you wish to continue the upload.
Quite a lot of image formats can be recognized by the first few bytes, the magic number. If the number matches you don't know whether the file is valid of course, but it may be used to match extension and magic number to prevent is really does not correspond at all.
Have a look at this page to check out some Java which checks mime-types. Do read the docs or source to check whether any given method requires the entire file, or can operate on the first few bytes. I've not used those libraries :)
Also check out this page which also lists some java libraries, and some papers on which detection is based.
Don't forget to put in some feedback if you managed to find something you like!
您不需要第三方库。您必须编写的代码很简单。
在处理上传时,请按扩展名过滤文件。这并不完美,但可以解决大多数情况。
但是,这意味着文件已经上传到服务器。您可以在客户端使用一些 JavaScript 来执行相同的操作 - 检查文件上传组件的值是否包含允许的文件类型 -
.jpg
、.png< /代码>等
You don't need 3rd party libraries. The code you have to write is simple.
At the point you are handling your uploads, filter the files by their extension. This isn't perfect, but will account for most of the cases.
However, this would mean files are already uploaded to the server. You can use a bit of javascript on the client-side to perform the same operation - check whether the value of the file-upload component contains an allowed file type -
.jpg
,.png
, etc.