通过HttpURLConnection下载图片到本地--批量下载

一.背景说明

  这篇文章讲述的是批量下载附件,在上一篇文章中,介绍了下载单个附件(上一篇文章)。

二.实现思路

  主要的实现思路:创建文件夹->文件夹中创建需要下载的文件->压缩文件夹->下载zip->删除文件夹

三.代码

1.html

    /*
     * 批量下载附件
     */
    $("#merchantApproval-annes-center-tb .batchDownloadButton").click(function(){
        //获取附件列表的所有记录
        var rows = $("#merchantApproval-annes-center-dg").datagrid("getRows");
        //如果记录不为空
        if(rows.length>0){
            var imgList = "";
            var imgName = "";
            //遍历记录,获取图片地址列表和图片名称列表,以“|”隔开
            $.each(rows,function(index,obj){
                imgList = imgList + obj.annUrl + "|";
                imgName = imgName + obj.annName + "|";
            });
            //临时构造一个form表单,用来发送post请求
            //如果直接发送get请求,可能因为url过长导致失败,所以就需要发送post请求
            var rootDiv = $("#merchantApproval-annes");
            rootDiv.append("<form id='batchDownloadForm' method='post' action='${ctx}/approvalImageHandle.do?method=batchDownload'>"
                    +"<input name='imgList' value="+ imgList +">"
                    +"<input name='imgName' value="+ imgName +">"
                    +"</form>");
            //发送完请求后,删除掉这个临时的form
            $("#batchDownloadForm").submit().remove();
        }else{
            //提示用户
            showTip("没有可以下载的数据!");
        }
    });

2.Controller

   /**
     * 批量下载附件<br/>
     * 主要的实现思路:创建文件夹->文件夹中创建需要下载的文件->压缩文件夹->下载zip->删除文件夹
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(params = "method=batchDownload")
    public void batchDownload(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //图片资源地址
        String _imgList = request.getParameter("imgList");
        //图片名称
        String _imgName = request.getParameter("imgName");
        //图片资源地址列表
        String[] imgUrlList = _imgList.split("\\|");
        //图片名称列表
        String[] imgNameList = _imgName.split("\\|");
        //媒体服务器的地址
        String imgShowUrl = (String)request.getSession().getAttribute("imgShowUrl");
        //创建文件夹
        //request.getRealPath()方法使用request.getSession().getServletContext().getRealPath()代替
        File fileDir = new File(request.getSession().getServletContext().getRealPath("/") + "/batchDownload");
        if(!fileDir.exists()){
            fileDir.mkdir();
        }
        /*
         * 在batchDownload文件夹下创建每个文件
         */
        for(int i = 0; i < imgUrlList.length; i++){
            //图片资源地址列表加上imgShowUrl构成完整的url地址
            imgUrlList[i] = imgShowUrl + "/" + imgUrlList[i];
            URL url = new URL(imgUrlList[i]);
            HttpURLConnection httpURL = (HttpURLConnection)url.openConnection();
            //设置网络连接超时时间
            httpURL.setConnectTimeout(5000);
            //设置应用程序要从网络连接读取数据
            httpURL.setDoInput(true);
            httpURL.setRequestMethod("GET");
            int responseCode = httpURL.getResponseCode();
            if(responseCode == 200){
                //如果响应为“200”,表示成功响应,则返回一个输入流
                InputStream inputStream = httpURL.getInputStream();
                //文件输出流,创建文件
                FileOutputStream outputStream = new FileOutputStream(fileDir.getPath() + "\\" + (i+1) + "_" + imgNameList[i]);
                byte[] data = new byte[1024];
                int len = 0;
                while((len = inputStream.read(data)) > 0){
                    outputStream.write(data, 0, len);
                }
                outputStream.close();
                inputStream.close();
            }
        }
        /*
         * 文件创建完毕后压缩文件夹为zip
         */
        Date date = new Date();
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename="+ "batchDownload" +date.getTime()+".zip");
        //创建压缩文件输出流
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        //获取文件列表
        File[] files = fileDir.listFiles();
        for(int i = 0; i < files.length; i++){
            File f = files[i];
            zos.putNextEntry(new ZipEntry(f.getName()));
            FileInputStream fis = new FileInputStream(f);
            byte[] bs = new byte[1024];
            int len = 0;
            while((len = fis.read(bs)) > 0){
                zos.write(bs, 0, len);
            }
            fis.close();
        }
        zos.flush();
        zos.close();
        /*
         * 文件压缩完毕后删除创建的文件夹
         */
        if(fileDir.exists()){
            for(int i = 0; i< files.length; i++){
                files[i].delete();
            }
        }
    }

 

posted @ 2016-06-03 16:24  向东方  阅读(1057)  评论(0编辑  收藏  举报