How can i set localized filenames in java.Currently everytime i click on a localized file having a non-ascii filename in my application, the windows save dialog box pops out, but it isnt displaying the filename properly if the charset is anything above ISO-88859-1.
This is my code which is saving the file.
InputStream inputStream = null;
try {
response.resetBuffer();
response.setContentType(fileStream.getContentType());
response.setContentLength((int) fileStream.getContentLength());
response.addHeader("Content-Disposition",
"attachment;filename=\"" + fileName + "\"");
ServletOutputStream stream = response.getOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
int total = 0;
inputStream = fileStream.getInputStream();
while ((read = inputStream.read(buffer)) > 0) {
stream.write(buffer, 0, read);
total += read;
}
response.flushBuffer();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
I would be very helpful if someone could share their ideas on how to resolve this issue. Thanks in advance.
What gustafc says is correct, but it doesn't get you where you want to be. RFC 2231 allows you to use an alternative format for non-ASCII Content-Type
and Content-Disposition
parameters, but not all browsers support it. The way that's most likely to work, unfortunately, is to ignore what RFC 2183 says and use RFC 2047 encoded-words in the response:
response.addHeader("Content-Disposition", "attachment; " +
"filename=\"" + MimeUtility.encodeWord(fileName, "utf-8", "Q") + "\"");
Note that this may not work for all browsers. Some variants of IE require that you URL-encode the value instead:
response.addHeader("Content-Disposition",
"attachment; filename=" + URLEncoder.encode(filename, "utf-8"));
I faced similar problems with filenames containing greek characters.I used the code provided in the answer above (my thanks to dkarp) combined with detecting which browser is used. this is the result:
String user_agent = request.getHeader("user-agent"); boolean isInternetExplorer = (user_agent.indexOf("MSIE") > -1); if (isInternetExplorer) { response.setHeader("Content-disposition", "attachment; filename=\"" + URLEncoder.encode(filename, "utf-8") + "\""); } else { response.setHeader("Content-disposition", "attachment; filename=\"" + MimeUtility.encodeWord(filename) + "\""); }
I tested it with firefox 3.6 , chrome 10.0 and Internet Explorer 8 and it seems to work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With