使用response.setHeader("Content-Disposition","attachment;filename="+fName)下载文件,中文文件名无法显示的问题

response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment;filename="+file_name);
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = new FileInputStream(file_uri());
byte[] buffer = new byte[1024];
int i = -1;
while ((i = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, i);
}
outputStream.flush();
outputStream.close();
inputStream.close();

假设file_nam的内容是:“工程文档.docx”

那么下载的结果就是一个名为“docx”的文件(文件名+后缀名),显然,文件名中的中文字符丢失了

上网查了资料,解决办法如下(我也感觉很不可思议,但的确管用了)

 

response.setContentType("application/x-download");
file_name = new String(file_name.getBytes(), "ISO-8859-1");
response.setHeader("Content-Disposition","attachment;filename="+file_name);
// 其他代码略

 

你可能感兴趣的:(java)