在执行write写入流到一定字节时会弹出下载对话框,当client端点击打开或是保存时,这时候会返回 true值,如果点击取消则返回IOException false,以此来判断客户端打开完之后执行的操作,特别注意的是当client端执行打开,保存,取消操作时会再次调用进入下载方法的Action,以此来结束所构建的流的状态,刚开始不知道什么原因,后来单步执行,才发现,不过有个问题就是,如果文件比较小,,只会执行一次.
对于构建输出流的时候要注意在适当的位置构建,不然在关闭的时候调用close()方法无法关闭输出流,将会导致该进程一致被占用.
java 代码
- public boolean downloadFile(HttpServletResponse response, String urlPath) {
- boolean isSuccess = true;
- String dst_fname = urlPath.substring(urlPath.lastIndexOf("\\") + 1);
- try {
- dst_fname = URLEncoder.encode(dst_fname, "utf-8");
- } catch (UnsupportedEncodingException e2) {
- }
- FileInputStream fis = null;
- BufferedInputStream bis=null;
- OutputStream os=null;
- BufferedOutputStream bos=null;
- try {
- response.reset();
- response.setContentType("application/x-download");
- response.setHeader("Content-disposition", "attachment; filename=\""
- + dst_fname + "\"");
-
- fis = new FileInputStream(urlPath);
-
- bis = new BufferedInputStream(fis);
- os = response.getOutputStream();
- bos = new BufferedOutputStream(os);
- byte[] buf = new byte[1024];
- int i = -1;
- while ((i = bis.read(buf)) != -1) {
- bos.write(buf, 0, i);
- }
- bos.flush();
- } catch (IOException e) {
- isSuccess = false;
- } catch (Exception e) {
- isSuccess = false;
- } finally {
- try {
- if (bos != null) {
- bos.close();
- bos=null;
- }
- if (os != null) {
- os.close();
- os=null;
- }
- if (bis != null) {
- bis.close();
- bis=null;
- }
- if(fis!=null){
- fis.close();
- fis=null;
- }
- } catch (IOException e) {
- isSuccess = false;
- }
- }
-
- return isSuccess;
- }