从本地下载固定的WORD模板

这篇博客展示了如何在Java后端控制器中实现从本地下载固定Word模板。通过设置响应头和输出流,将文件内容传输到浏览器,允许用户下载。代码中包含文件路径处理、字符编码转换以及文件输入输出流的管理和关闭。
摘要由CSDN通过智能技术生成

直接在controller中写的,前台使用的herf,因为是测试写的所以没有特别复杂

(动态往word中填数据以后用到会补充)

@SuppressWarnings("deprecation")
    @RequestMapping("downLoad")
    @ResponseBody
    public void downLoad(HttpServletRequest request, ModelMap model, HttpSession session, HttpServletResponse response) {
        String fileName ="bbb.doc"; //我的文件名
        try {
            request.setCharacterEncoding("utf-8");
            fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8");
            //获取文件路径
            String path = ServerDirUtil.dataTemplettRoot; //这个是util 获取文件的路径的
            String inpath = path + "/" +fileName;
               //设置向浏览器端传送的文件格式
            response.setContentType("application/x-download");
 
                 fileName =  CommonUtil.decode(fileName, "UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
                FileInputStream fis = null;
                OutputStream os = null;
                try {
                    os = response.getOutputStream();
                    fis = new FileInputStream(inpath);
                    byte[] b = new byte[1024 * 10];
                    int i = 0;
                    while ((i = fis.read(b)) > 0) {
                        os.write(b, 0, i);
                    }
                    os.flush();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (os != null) {
                        try {
                            os.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值