js实现文件下载

前台代码:

function exportReport(){var url = "后台处理方法地址";
        download(url);
    } 
    
    function download(url){
        Ext.Msg.wait("正在下载数据,请稍等。。。");
        if (!Ext.fly('downForm')){      //如果不存在一个id为"downForm"的form表单,则执行下面的操作
             //下面代码是在创建一个表单以及添加相应的一些属性
              var downForm = document.createElement('form');  //创建一个form表单
             downForm .id = 'downForm';   //该表单的id为downForm
              downForm .name = 'downForm';  //该表单的name属性为downForm
              downForm .className = 'x-hidden'; //该表单为隐藏的
              downForm .action = url;
              downForm .method = 'post';  //表单的提交方法

              document.body.appendChild(downForm ); //讲form表单追加到body里面
            }            
            Ext.fly('downForm').dom.submit(); //调用form表单的submit方法,提交表单,从而开始下载文件

            //如果存在id为downForm的表单,则将它移除掉
            if (Ext.fly('downForm')){      
               document.body.removeChild(downForm );      
            }
            Ext.Msg.hide();
    }

后台代码:

@RequestMapping(value="/exportExcel",method = {RequestMethod.POST,RequestMethod.GET},produces = "text/html; charset=UTF-8")
    public static void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        response.addHeader("Content-Disposition", "attachment;filename=exportInfo.xlsx");
        response.setContentType("application/octet-stream");try {
            //获取需要下载的文件
        File output = null;

               InputStream in = new FileInputStream(output); // 获取下载文件的输入流
               int count = 0;
               byte[] by = new byte[1024];
               // 通过response对象获取OutputStream流
               OutputStream out = response.getOutputStream();
               while ((count = in.read(by)) != -1) {
               out.write(by, 0, count);// 将缓冲区的数据输出到浏览器
               }
               in.close();
               out.flush();
               out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

posted @ 2022-03-11 16:18  JF_H  阅读(1082)  评论(0编辑  收藏  举报