Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 603
Ignacio Avatar asked Dec 27 '10 16:12

Ignacio


2 Answers

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.

like image 197
Martin v. Löwis Avatar answered Sep 22 '22 22:09

Martin v. Löwis


response.setCharacterEncoding("utf-8");

like image 35
Gursel Koca Avatar answered Sep 23 '22 22:09

Gursel Koca