最近做了一个文件下载的需求,但是下载的文件名称如果是中文名,下载后出现名称无法显示的问题。查看资料后最终解决了。
原因:
因为用post方式提交的,所以用Servlet做的,设置的头信息里面需要对文件名称做处理,Header中只支持ASCII,传输的文件名必须是ASCII否则当出现中文名文件时,就出现异常。
在网上找了方法,attachmentPath = URLEncoder.encode(attachmentPath,"UTF-8");发现这样还是不行,如图:
又重新试了attachmentPath = new String(attachmentPath.getBytes("UTF-8"), "ISO-8859-1");就可以了
代码如下:
@PostMapping("/download/{attachmentPath}")
public void exportVehicleInfo(HttpServletRequest req, HttpServletResponse resp,String attachmentPath) {
String fileName=attachmentPath;
log.info("上传的文件为:" + attachmentPath);
DataInputStream in = null;
OutputStream out = null;
try{
resp.reset();// 清空输出流
resp.setContentType("application/force-download");
resp.setCharacterEncoding("UTF-8");
attachmentPath = new String(attachmentPath.getBytes("UTF-8"), "ISO-8859-1");
//attachmentPath = URLEncoder.encode(attachmentPath,"UTF-8");
resp.setHeader("Content-Disposition", "attachment; filename=" + attachmentPath);// 设定输出文件头
String filePath = "C:\\Users\\Bairong\\Desktop\\Gao\\运营管理平台\\异议数据\\file\\";
String path = filePath + fileName;
log.info("上传的文件路径为:" + path);
//输入流:本地文件路径
in = new DataInputStream(
new FileInputStream(new File(path)));
//输出流
out = resp.getOutputStream();
//输出文件
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
} catch(Exception e){
e.printStackTrace();
resp.reset();
try {
OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");
String data = "<script language='javascript'>alert(\"\\u64cd\\u4f5c\\u5f02\\u5e38\\uff01\");</script>";
writer.write(data);
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}finally {
if(null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ISO-8859-1为什么可以: