JSP: get MIME type on file upload

I am doing a file upload and I want to get the Mime type from the downloaded file.

I tried to use request.getContentType () , but when I call:

String contentType = req.getContentType(); 

He will return:

multi-part / form data; border = --------------------------- 310662768914663

How can I get the correct value?

Thanks in advance

+6
java mime-types jsp servlets file-upload
source share
3 answers

It sounds like you are creating a multipart/form-data parser. I would not recommend doing this. Rather, use a decent one, such as Apache Commons FileUpload . For downloaded files, it offers FileItem#getContentType() to retrieve the specified content type, if any.

 String contentType = item.getContentType(); 

If it returns null (just because the client did not specify it), you can use ServletContext#getMimeType() based on the file name.

 String filename = FilenameUtils.getName(item.getName()); String contentType = getServletContext().getMimeType(filename); 

This will be allowed based on the <mime-mapping> entries in the servletcontainer default web.xml (in the case of, for example, Tomcat, it is present in /conf/web.xml ), as well as on the web.xml your web client, if any there is one that can expand / override the default collation for servletcontainer.

However, you need to remember that the value of the type of multi-page content is completely controlled by the client, and also that the file extension provided by the client does not have to represent the actual contents of the file. For example, a client may simply edit the file extension. Be careful when using this information in business logic.

Connected:

  • How to upload files to JSP / Servlet?
  • How to check if the downloaded file is an image?
+21
source share

just use:

 public String ServletContext.getMimeType(String file) 
0
source share

You can use MimetypesFileTypeMap

 String contentType = new MimetypesFileTypeMap().getContentType(fileName)); // gets mime type 

However, you would run into the overhead of editing the mime.types file if the file type is not already specified. (Sorry, I'm taking this back, as you can add instances to the card programmatically, and this will be the first thing it checks)

0
source share

All Articles