JSP:获取文件上传的MIME类型 [英] JSP: Get MIME Type on File Upload
问题描述
我试图使用请求。 我正在做一个文件上传,我想从上传的文件中获取Mime类型。 getContentType()
字符串contentType = req.getContentType();
它会返回:
lockquote
multipart / form-data; border = --------------------------- 310662768914663
如何获得正确的值?
在此先感谢
听起来好像你正在生长一个 multipart / form-data
解析器。我不会推荐这样做。而是使用像 Apache Commons FileUpload 体面的。对于上传的文件,它提供了一个 FileItem#getContentType()
来提取客户指定的内容类型(如果有的话)。
String contentType = item.getContentType();
如果它返回 null
客户端没有指定它),那么你可以利用
$ rel =nofollow noreferrer> ServletContext#getMimeType()
。
字符串文件名= FilenameUtils.getName(item.getName());
String contentType = getServletContext()。getMimeType(filename);
这将根据< mime-mapping>
servletcontainer默认的 web.xml
中的条目(例如Tomcat,它存在于 /conf/web.xml中
)以及web应用程序的 web.xml
(如果有的话),它们可以扩展/覆盖servlet容器的默认映射。
然而,您需要记住,多部分内容类型的值完全由客户端控制,并且客户端提供的文件扩展名不一定需要表示实际的 em>文件内容。例如,客户端可以编辑文件扩展名。在业务逻辑中使用这些信息时要小心。
相关:
- <如何在JSP / Servlet中上传文件? li>
- 如何检查上传的文件是否为图片?
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
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 a FileItem#getContentType()
to extract the client-specified content type, if any.
String contentType = item.getContentType();
If it returns null
(just because the client didn't specify it), then you can take benefit of ServletContext#getMimeType()
based on the file name.
String filename = FilenameUtils.getName(item.getName());
String contentType = getServletContext().getMimeType(filename);
This will be resolved based on <mime-mapping>
entries in servletcontainer's default web.xml
(in case of for example Tomcat, it's present in /conf/web.xml
) and also on the web.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:
这篇关于JSP:获取文件上传的MIME类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!