欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringMVC如何把后台文件打印到前台

时间:2021-03-11 10:06:26|栏目:JAVA代码|点击:

实现效果如下:

代码为:

@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, 0, 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

上一篇:配置Spring4.0注解Cache+Redis缓存的用法

栏    目:JAVA代码

下一篇:IDEA解决src和resource下创建多级目录的操作

本文标题:SpringMVC如何把后台文件打印到前台

本文地址:http://www.codeinn.net/misctech/78531.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有