【背景】需求要求从服务器中下载已导出的用户信息Excel表格文件到用户本地
【代码】
/**
* 下载生成的所有在线/离线用户信息表格
* @param request
* @param response
* @return 压缩文件
* @throws FTPConnectionClosedException
* @throws IOException
*/
public File downloadExcel (HttpServletRequest request, HttpServletResponse response)
throws FTPConnectionClosedException, IOException {
File file = new File(zipPath);
FileOutputStream fos = new FileOutputStream(file);
ZipUtils.toZip(path, fos, true);
//1.获取要下载的文件的绝对路径
String realPath = zipPath;
//2.获取要下载的文件名
String fileName = realPath.substring(realPath.lastIndexOf(File.separator)+1);
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
//3.设置content-disposition响应头控制浏览器以下载的形式打开文件
response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(),"utf-8"));
//获取文件输入流
InputStream in = new FileInputStream(realPath);
int len = 0;
byte[] buffer = new byte[1024];
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
//将缓冲区的数据输出到客户端浏览器
out.write(buffer,0,len);
}
in.close();
return file;
}
【问题】如何将乱码转换为正常的中文?
尝试一:https://segmentfault.com/a/11... 按照此链接中的标准设定HTTP头字段Content-Disposition未奏效;