zoukankan      html  css  js  c++  java
  • 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

    原创文章,欢迎转载,转载请注明出处!

  • 相关阅读:
    React开发实时聊天招聘工具 -第六章 登陆注册(2)
    React开发实时聊天招聘工具 -第六章 登陆注册(1)
    温习 socket http tcp
    高阶组件简介
    计算机组成原理(7)——输入、输出系统
    计算机组成原理(6)——总线
    计算机组成原理(5)——中央处理器
    计算机组成原理(4)——指令系统
    计算机组成原理(3)——存储层次结构
    计算机组成原理(2)——数据的表示与运算
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/springPrintFile.html
Copyright © 2011-2022 走看看