如何在servlet上设置内容类型 [英] How to set the content type on the servlet
问题描述
我正在使用一个简单的servlet,它将数据库中的文档内容作为字节数组发回。我想设置一个内容键入,以便在通过doGet()调用检索时具有适当的扩展名。
I am using a simple servlet which sends back document contents from the database as a byte array. I would like to set a content type so that it has an appropriate extension while it is being retrieved via a doGet() call.
我确实将文档的类型存储为数据库中的元数据(例如png,gif,png,xls,docx ...)。
I do have the type of the document stored as a metadata in the database (e.g. png, gif, png, xls, docx ...).
- 我应该设置什么作为内容类型,以便它保留文件扩展名?
- 下载的文件名为doc,如何在servlet上设置文件名以便下载数据。
推荐答案
我应该将什么设置为内容类型,以便它保留了文件扩展名吗?
使用 ServletContext#getMimeType()
根据文件名获取mime类型。
Use ServletContext#getMimeType()
to get the mime type based on the file name.
String mimeType = getServletContext().getMimeType(filename);
servletcontainer通常已在其自己的 web中提供默认的mime类型映射。 XML
。如果要覆盖或添加其他内容,请将其作为新的mime映射放在webapp的 web.xml
中。例如,
The servletcontainer usually already provides a default mime type mapping in its own web.xml
. If you want to overridde or add some other, then put it as new mime mappings in webapp's web.xml
. E.g.
<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>
最后将其设置为 Content-Type
响应头:
Finally set it as the Content-Type
response header:
response.setContentType(mimeType);
下载的文件名为doc,如何在servlet上设置要下载的数据的文件名。
将其添加到servlet URL,因为某些浏览器(如MSIE)会忽略内容处置的 filename
属性。
Add it to the servlet URL because some browsers like MSIE ignores the filename
attribute of the content disposition.
<a href="download/filename.ext">download filename.ext</a>
如果servlet映射到 / download / * <的URL模式/ code>,然后你可以按如下方式获得它
If the servlet is mapped on an URL pattern of /download/*
, then you can obtain it as follows
String filename = request.getPathInfo().substring(1);
最后在 Content-Disposition
中设置它标题以及使普通浏览器感到高兴:
Finally set it in the Content-Disposition
header as well to make normal browsers happy:
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
如果您不在DB中存储文件名而是ID或其他内容,则将其用作文件名而不是。
If you don't store filenames in DB but rather IDs or something, then use it as filename instead.
<a href="download/${file.id}.${file.ext}">download ${file.id}.${file.ext}</a>
然后在servlet中
And then in the servlet
String filename = request.getPathInfo().substring(1);
String id = filename.split("\\.")[0];
// Obtain from DB based on id.
这篇关于如何在servlet上设置内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!