java 如何为文件下载 servlet 设置 UTF-8 编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4540003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set UTF-8 encoding for a file download servlet
提问by Ignacio
I have a servlet that sends a file to the browser.
我有一个向浏览器发送文件的 servlet。
I send this headers in the servlet.
我在 servlet 中发送这个标头。
if (request.isSecure()) {
response.addHeader("Pragma", "no-cache");
response.addHeader("Expires", "-1");
response.addHeader("Cache-Control", "no-cache");
} else {
response.addHeader("Cache-Control", "private");
response.addHeader("Pragma", "public");
}
if (isIE) {
response.addHeader("Content-Disposition", "attachment; filename=\"" + encName + "\"" );
response.addHeader("Connection", "close");
response.setContentType("application/force-download; name=\"" + encName + "\"" );
} else {
response.addHeader("Content-Disposition", "attachment; filename=\"" + encName + "\"" );
response.setContentType("application/octet-stream; name=\"" + encName + "\"" );
if (contentLen > 0) {
response.setContentLength(contentLen);
}
}
Then i send the file to the browser, but i'm having troubles with the file encoding. The content of the file is UTF-8 but i don't know how to send a header for this.
然后我将文件发送到浏览器,但我遇到了文件编码问题。该文件的内容是 UTF-8,但我不知道如何为此发送标头。
Does anyone have idea how can i do?
有谁知道我该怎么办?
回答by Martin v. L?wis
There is no need to tell the browser that the file is UTF-8 encoded. By setting the content type to application/octet-stream, you specify that the file must not be interpreted, and may not be plain text at all.
无需告诉浏览器该文件是 UTF-8 编码的。通过将内容类型设置为 application/octet-stream,您可以指定该文件不得被解释,并且可能根本不是纯文本。
If you absolutely want to declare an encoding, stop declaring the file as application/octet-stream, and declare it as "text/plain; charset=utf-8" instead.
如果您绝对要声明编码,请停止将文件声明为 application/octet-stream,而将其声明为“text/plain; charset=utf-8”。
回答by Gursel Koca
response.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");