我正在编写一个简单的文件下载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
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();
}
Run Code Online (Sandbox Code Playgroud)