Java下载功能代码

    @RequestMapping("download.do")
    public String download(@RequestParam("url") String url, HttpServletResponse response) throws IOException {
        //获取完整文件路径
        String filePath = "D:\\test\\result" + url;

        File file = new File(filePath);
        if (file.exists()) {
            System.out.println("开始传输");
            //设置传输格式,当前文件为excel
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("result" + url, "UTF-8"));
            OutputStream os = null;
            InputStream is = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] buffer = new byte[1024]; // 文件流缓存池
            int data = 0;
            while ((data = is.read(buffer)) != -1) {
                //传输
                os.write(buffer, 0, data);
            }
            os.flush();
            is.close();
            os.close();
            file.delete();
            return null;
        }
        return null;
    }

注意:下载不能使用ajax请求,因为ajax无法调取浏览器下载功能,只能通过地址访问进行下载。


版权声明:本文为weixin_42440765原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。