亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringMVC如何把后臺(tái)文件打印到前臺(tái)

 更新時(shí)間:2020年09月25日 08:58:52   投稿:yaominghui  
這篇文章主要介紹了SpringMVC如何把后臺(tái)文件打印到前臺(tái),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

實(shí)現(xiàn)效果如下:

代碼為:

@RequestMapping(value = "/tools/printContract")
public void cell(HttpServletResponse response,HttpServletRequest request,String outName) {
  //根據(jù)outName獲取到保存在服務(wù)器上的文件
  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, 0, n);
    }
    buffer = bos.toByteArray();
  } catch (Exception e) {
    // e.printStackTrace();
  }
  return buffer;
}

需要注意:返回值的類型是void 而不是String,不能返回到某一個(gè)頁面,否則服務(wù)器會(huì)拋出IllegalStateException異常,雖然在頁面上表現(xiàn)不出來。

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論