1. 程式人生 > 程式設計 >SpringMVC如何把後臺檔案列印到前臺

SpringMVC如何把後臺檔案列印到前臺

實現效果如下:

SpringMVC如何把後臺檔案列印到前臺

程式碼為:

@RequestMapping(value = "/tools/printContract")
public void cell(HttpServletResponse response,HttpServletRequest request,String outName) {
  //根據outName獲取到儲存在伺服器上的檔案
  String filePath = request.getSession().getServletContext().getRealPath(ImgUtil.TOOLS_PATH+ImgUtil.TOOLS_TXT)+'/'+outName+".txt";
  try(OutputStream out = response.getOutputStream()) {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String dateString = formatter.format(currentTime);
    //fileName是輸出的檔案的名字(不支援中文),包括了字尾
    String fileName = "EncryptFile_" + dateString + ".txt";
    byte[] bytes = FileEcodeUtil.file2byte(filePath);
    response.setContentType("application/x-msdownload");
    response.setHeader("Content-Disposition","attachment;filename=" + fileName);
    response.setContentLength(bytes.length);
    out.write(bytes);
    out.flush();
  } catch (IOException e) {
  //e.printStackTrace();
  }
}

//上面用到的file2byte方法為:
public static byte[] file2byte(String filePath) {
  byte[] buffer = null;
  File file = new File(filePath);
  try (FileInputStream fis = new FileInputStream(file);
     ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
    byte[] b = new byte[1024];
    int n;
    while ((n = fis.read(b)) != -1) {
      bos.write(b,n);
    }
    buffer = bos.toByteArray();
  } catch (Exception e) {
    // e.printStackTrace();
  }
  return buffer;
}

需要注意:返回值的型別是void 而不是String,不能返回到某一個頁面,否則伺服器會丟擲IllegalStateException異常,雖然在頁面上表現不出來。

  java.lang.IllegalStateException: Cannot create a session after the response has been committed

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。