天天看點

java 如何實作導出檔案

java 如何實作導出檔案

 上面的圖檔比較模糊,下面我們來看看導出的具體的例子

@RequestMapping(value = "/download", method = RequestMethod.GET)
  @ResponseBody
  public void testDownload(HttpServletResponse res) {
    String fileName = "aaa.txt";
      res.setHeader("content-type", "text/plain");
    res.setHeader("content-type", "application/x-msdownload;");
    res.setContentType("text/plain; charset=utf-8");
    res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;

    try {
      os = res.getOutputStream();
      bis = new BufferedInputStream(new FileInputStream(new File("C://Users//lxn//Desktop//aaa.txt")));
      int i = bis.read(buff);

      while (i != -1) {
        os.write(buff, 0, buff.length);
        os.flush();
        i = bis.read(buff);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (bis != null) {
        try {
          bis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    System.out.println("export file finish");
  }      

這個是接口,那麼前台怎麼處理

$("#dcbtn").click(function() {
        var serviceUrl = getProjectURL();
        window.open(serviceUrl + "fpdc/download");
    })      

這樣就實作了檔案的導出,我們直接用window.open(+資源接口+)

而不是對其傳回結果進行window.open

繼續閱讀