java的下载功能

1.jsjavascript

window.location.href = "/macModel/file/download?path="+a.download;  //a.download=a.xls文件

2.controller文件java

@RequestMapping("/file/download")
    public void fileDownload(HttpServletResponse response, String path) {
        //获取网站部署路径(经过ServletContext对象),用于肯定下载文件位置,从而实现下载
//        String path ="/Users/guanguan/workspace/rifle/static/excel/m2017_11_09_19_14_59.xls";
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        String fileName = path.substring(path.lastIndexOf("/")+1);
        //2.设置文件头:最后一个参数是设置下载文件名
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        ServletOutputStream out;
        //经过文件路径得到File对象
        File file = new File(path);

        try {
            FileInputStream inputStream = new FileInputStream(file);

            //3.经过response获取ServletOutputStream对象(out)
            out = response.getOutputStream();

            byte[] b = new byte[100];
            int len;
            try {
                while ((len = inputStream.read(b)) > 0) {
                    response.getOutputStream().write(b, 0, len);
                }
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.flush();

            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
     }
相关文章
相关标签/搜索