今天在使用spring進行檔案下載是,總報錯: java.lang.IllegalStateException: getOutputStream() has already been calle

來源:互聯網
上載者:User

解決辦法:

  把對應的action的返回設定為空白,即可輕鬆解決。

例如:

  @ActionAnnotation(name = "產生結婚報告文檔並下載", group = "查詢")
    public ModelAndView createMarriage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Management management = managementService.query(request.getParameter("mm_id"));
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("management", management);
        model.put("management", management);
        String view = SystemParameter.get("marriage");
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(SystemParameter.get("tempDirSoldier") + "/marriage.ftl", "utf-8");
        String temp = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        File file = new File(getServletContext().getRealPath(view));
        FileUtils.writeStringToFile(file, temp, "utf-8");
        response.setContentType("text/html; charset=GBK");
        response.setContentType("application/x-msdownload");   //設定response的編碼方式
        response.setContentLength((int) file.length());   //寫明要下載的檔案的大小
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(view.getBytes("gbk"), "iso-8859-1"));//解決中文亂碼
        FileInputStream fis = new FileInputStream(file);   //建立輸入資料流
        BufferedInputStream buff = new BufferedInputStream(fis);    //建立檔案緩衝
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024]; //設定緩衝大小
        long k = 0; //用於判斷檔案長度是否為0
        while (k < file.length()) {
            int j = buff.read(b, 0, 1024);
            k += j; //  累計檔案長度
            out.write(b, 0, j);
        }
        out.flush();  //將檔案資料重新整理到使用者名稱電腦上
        fis.close();
        out.close();
        file.delete(); // 刪除臨時檔案
        return  null;
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.