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();
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM