How to set content type on servlet

I use a simple servlet that sends back the contents of a document from the database as a byte array. I would like to set the type content so that it has the corresponding extension while it is retrieved using the doGet () call.

I have a type of document stored in metadata in a database (e.g. png, gif, png, xls, docx ...).

  • What should I set as a content type so that it retains the file extension?
  • The file is loaded with the name "doc", how to set the file name to the servlet for the loaded data.
+7
source share
2 answers

What should I set as a content type so that it retains the file extension?

Use ServletContext#getMimeType() to get the mime type based on the file name.

 String mimeType = getServletContext().getMimeType(filename); 

Servletcontainer usually already provides default mime type mapping in its own web.xml . If you want to override or add another one, then set it as the new mime mappings in webapp web.xml . For example.

 <mime-mapping> <extension>docx</extension> <mime-type>application/vnd.openxmlformats-officedocument.wordprocessingml.document</mime-type> </mime-mapping> <mime-mapping> <extension>xlsx</extension> <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type> </mime-mapping> 

Finally, set it as the header of the Content-Type response:

 response.setContentType(mimeType); 

The file is loaded with the name "doc", how to set the file name to the servlet for the loaded data.

Add it to the servlet URL because some browsers, such as MSIE, ignore the filename attribute to host content.

 <a href="download/filename.ext">download filename.ext</a> 

If the servlet appears in the URL /download/* pattern, you can get it as follows

 String filename = request.getPathInfo().substring(1); 

Finally, set it to the Content-Disposition header to make normal browsers happy:

 response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); 

If you do not store the file names in the database, but rather identifiers or something else, use the file name instead.

 <a href="download/${file.id}.${file.ext}">download ${file.id}.${file.ext}</a> 

And then to the servlet

 String filename = request.getPathInfo().substring(1); String id = filename.split("\\.")[0]; // Obtain from DB based on id. 
+12
source
  • What should I set as a content type so that it saves the file extension?

You can use the setContentType method of the response object to set the mime. eg:

 response.setContentType("your-correct-mime-here"); 

2. The file is uploaded with the name "doc", how can I set the file name on the servlet for the data being uploaded

You can set the file name of the downloaded file by setting the correct header. You can use Content-Disposition as shown below:

 response.setHeader("Content-Disposition", "attachment; filename=\"" + your_file_name + "\""); 
+8
source

All Articles