当前位置: 代码迷 >> J2EE >> struts2里关于文件上载一个有关问题
  详细解决方案

struts2里关于文件上载一个有关问题

热度:32   发布时间:2016-04-22 00:49:50.0
struts2里关于文件下载一个问题
我jsp页面全部采用utf8编码,配置跟网上的例子差不多,就是在
public InputStream getDownloadFile() throws UnsupportedEncodingException, FileNotFoundException
{
fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");/// 这里加了一句,不加是乱码
  return ServletActionContext.getServletContext().getResourceAsStream(
this.getSavePath() + this.getFilePath() + fileName); // --------------1
// File file=new File(ServletActionContext.getServletContext().getRealPath(this.getSavePath() + this.getFilePath() + fileName));
// System.out.println(file.exists()); // ------------------------------------------- testA
// FileInputStream stream = new FileInputStream(file);
// System.out.println(stream); // ------------------------------------------- testB
// return stream;// -----------------------------------2
   
  }
结果,文件里没有中文时可以完美下载,但但下载中文文件是,debug时发现fileName经过编码后是中文显示,无论采用1,还是2的方法,程序都弹出ie的一个错误信息(不是程序出错,直接在浏览器弹出ie出错窗口),说是“Internet Explorer 无法下载......,”,而testA和testB的结果分别是true,java.io.FileInputStream@153b098,我在网上找了很久,好像没发现有碰到同样情况的,请大家帮帮忙!!

------解决方案--------------------
HttpServletResponse response = ServletActionContext.getResponse();
 
response.reset();
response.setContentType("application/vnd.ms-excel;charset=GBK");
try {
response.setHeader("Content-Disposition" ,"attachment;filename="+new String((outName).getBytes(),"iso-8859-1"));
OutputStream os = response.getOutputStream();

byte[] buffer = new byte[1024];
BufferedInputStream reader = new BufferedInputStream(
new FileInputStream(strFileUrl));

while (reader.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close(); 
}catch (ClientAbortException e) {
// e.printStackTrace();
}catch (java.net.SocketException e) {
// e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}

这是我的
  相关解决方案