我正在编写一个简单的文件下载Servlet,但无法获得正确的文件名。尝试使用现有答案中所见的URLEncoding和MimeEncoding文件名,但它们都没有起作用。
以下代码段中的fileData对象包含mime类型、byte[]内容和文件名,需要至少ISO-8859-2字符集,ISO-8859-1不够用。
如何使浏览器正确显示下载的文件名?
这是一个文件名的例子:árvíztűrőtükörfúrógép.xls,结果为:árvíztqrptükörfúrógép.xls
以下代码段中的fileData对象包含mime类型、byte[]内容和文件名,需要至少ISO-8859-2字符集,ISO-8859-1不够用。
如何使浏览器正确显示下载的文件名?
这是一个文件名的例子:árvíztűrőtükörfúrógép.xls,结果为:árvíztqrptükörfúrógép.xls
protected void renderMergedOutputModel(Map model, HttpServletRequest req, HttpServletResponse res) throws Exception {
RateDocument fileData = (RateDocument) model.get("command.retval");
OutputStream out = res.getOutputStream();
if(fileData != null) {
res.setContentType(fileData.getMime());
String enc = "utf-8"; //tried also: ISO-8859-2
String encodedFileName = fileData.getName();
// also tried URLencoding and mime encoding this filename without success
res.setCharacterEncoding(enc); //tried with and without this
res.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
res.setContentLength(fileData.getBody().length);
out.write(fileData.getBody());
} else {
res.setContentType("text/html");
out.write("<html><head></head><body>Error downloading file</body></html>"
.getBytes(res.getCharacterEncoding()));
}
out.flush();
}