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];