struts1.x 文件下载(解决下载过程中后台报错问题)
最近发现struts1.x在下载文件时,当点击下载时,在弹出的保存、打开窗口时选择取消,后台报错,在网上查询了很久,用网络上的方法都没有解决这个问题,经测试发现struts2的文件下载并没有出现类似问题,因此查看了下struts2的源代码,修改了下载的代码,完美解决这个问题,在此备份以便以后查看
?
InputStream inputStream = null;OutputStream os = null;try {response.addHeader("Content-Type", "application/octet-stream;charset=UTF-8");response.addHeader("Content-Disposition", "attachment;filename=download.txt"); //下载时文件名称response.addHeader("Pragma", "no-cache");response.addHeader("Cache-Control", "no-cache");byte[] buff = new byte[8192];inputStream = new FileInputStream("D://2.txt"); //文件路径os = response.getOutputStream();int count = 0;while (-1 != (count = inputStream.read(buff))) {os.write(buff, 0, count);}os.flush();} catch (Exception e) {e.printStackTrace();} finally {if(inputStream != null) {inputStream.close();}if(os != null) {os.close();}}