How to set UTF-8 encoding for a file download servlet
I have a servlet that sends a file to the browser.
I send this headers in the 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.
Does anyone have idea how can i do?
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.
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.
response.setCharacterEncoding("utf-8");
精彩评论