JavaEE文件下载知识(一)

js端代码:

function download(){
    $('.filedownload').click(function(){
        var a=$(this).attr('data');//获取a的相对路径
        var rootPath = getContextPath()+"/download/wordFiles";//后台服务器地址,将参数传到后台中
             if(a){
                    var form=$("<form>");//定义一个form表单
                    form.attr("style","display:none");
                    form.attr("target","");
                    form.attr("method","post");
                    form.attr("action",rootPath);
                    var fileInput=$("<input>");
                    fileInput.attr("type","hidden");
                    fileInput.attr("id","filepath");//设置属性的名字
                    fileInput.attr("name","filepath");//设置属性的名字
                    fileInput.attr("value",a);//设置属性的值
                    $("body").append(form);//将a单放置在web中
                    form.append(fileInput);
                    form.submit();//表单提交   
                    form.remove();
                }
    })
}

js端代码的核心就是虚拟form表单标签,进行虚拟提交表单,向服务器传递参数,进行下一步操作

javaWeb端(SpringMVC)相应代码:

@RequestMapping(value="/download/wordFiles",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public void  downloadtemplatefile(HttpServletRequest request, HttpServletResponse response ,String filepath){



        try{
            if(filepath==null || "".equals(filepath))
            {
                throw new Exception("要下载的文件id不能为空");
            }
            String realPath=filepath;
            //设置下载文件的头信息
            String name = filepath.substring(filepath.lastIndexOf("/"));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");  
            response.setHeader("Content-disposition", "attachment; filename="+ new String(name.getBytes("utf-8"), "ISO8859-1")); 
            //将查询到的数据信息填充到模板中生成完整的文件
            String fullfilename = request.getSession().getServletContext().getRealPath(realPath);
            System.out.println(fullfilename);
            XWPFTemplate xwpfTemplate;
            xwpfTemplate =  XWPFTemplate.compile(fullfilename);
            OutputStream out = response.getOutputStream();
            xwpfTemplate.write(out);
            out.flush();
            out.close();

        }catch(Exception e)
        {
            logger.error(e.getLocalizedMessage(), e);
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值