在使用struts2实现下载带有中文文字的文件时出现乱码问题,即弹出的对话框中文件名为乱码,而且无法无法下载,现就该问题给出如下解决方案:
1、页面请求:<a id="download" href="follow!download?fileName=<s:property value="imageList0.imageName"/>"><s:property value="imageList0.imageName"/></a>
2、action处理:
private String fileName;
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
try {
fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fileName;
}
/**
* 文件下载
*/
public String download(){
return "download";
}
/**
* 获取下载文件流
* @return
*/
public InputStream getInputStream(){
String realPath = ServletActionContext.getServletContext().getRealPath("/upload") + "/" + fileName;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(realPath));
} catch (FileNotFoundException e) {
log.error(e);
}
return inputStream;
}
返回处理:
@Result(name = "download", type="stream", params={"contentType","application/octet-stream","inputName","inputStream","contentDisposition","attachment;filename=${fileName}","bufferSize","4096"})})
重点是红色标注部分,否则一样不会解决乱码问题。