JSP:获取文件上传的 MIME 类型
我正在上传文件,我想从上传的文件中获取 Mime 类型。
我试图使用 request.getContentType(),但是当我调用:
String contentType = req.getContentType();
它将返回:
多部分/表单数据;边界=----------------------------310662768914663
如何获得正确的值?
提前致谢
I'm doing a file upload, and I want to get the Mime type from the uploaded file.
I was trying to use the request.getContentType(), but when I call:
String contentType = req.getContentType();
It will return:
multipart/form-data; boundary=---------------------------310662768914663
How can I get the correct value?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来好像您正在自行开发一个
multipart/form-data
解析器。我不建议这样做。而是使用像 Apache Commons FileUpload 这样的像样的文件上传。对于上传的文件,它提供了FileItem#getContentType()
提取客户端指定的内容类型(如果有)。如果它返回
null
(只是因为客户端没有指定它),那么您可以利用ServletContext#getMimeType()
基于文件名。这将根据 servletcontainer 的默认
web.xml
中的
条目来解决(例如,对于 Tomcat,它存在于/conf/ 中) web.xml
)以及您的 web 应用程序的web.xml
(如果有),它可以扩展/覆盖 servletcontainer 的默认映射。但是,您需要记住,多部分内容类型的值完全由客户端控制,并且客户端提供的文件扩展名不一定需要表示实际的文件内容。例如,客户端可以只编辑文件扩展名。在业务逻辑中使用此信息时要小心。
相关:
It sounds like as if you're homegrowing a
multipart/form-data
parser. I wouldn't recommend to do that. Rather use a decent one like Apache Commons FileUpload. For uploaded files, it offers aFileItem#getContentType()
to extract the client-specified content type, if any.If it returns
null
(just because the client didn't specify it), then you can take benefit ofServletContext#getMimeType()
based on the file name.This will be resolved based on
<mime-mapping>
entries in servletcontainer's defaultweb.xml
(in case of for example Tomcat, it's present in/conf/web.xml
) and also on theweb.xml
of your webapp, if any, which can expand/override the servletcontainer's default mappings.You however need to keep in mind that the value of the multipart content type is fully controlled by the client and also that the client-provided file extension does not necessarily need to represent the actual file content. For instance, the client could just edit the file extension. Be careful when using this information in business logic.
Related:
只需使用:
just use:
您可以使用 MimetypesFileTypeMap
但是,您会遇到如果文件类型尚未列出,则编辑 mime.types 文件的开销。 (抱歉,我收回这一点,因为您可以以编程方式将实例添加到地图中,这将是它检查的第一个位置)
You could use MimetypesFileTypeMap
However, you would encounter the overhead of editing the mime.types file, if the file type is not already listed. (Sorry, I take that back, as you could add instances to the map programmatically and that would be the first place that it checks)