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);
        }
    }

猜你喜欢

转载自blog.csdn.net/technology_liu/article/details/79713924