栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/131526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号