Java 从服务器上批量打包(zip)下载文件到本地

该博客介绍了如何使用Java处理从服务器批量打包并下载文件到本地的逻辑。通过一个控制器方法`downloads`接收参数,结合JSP页面展示文件列表,并提供选择文件的功能。用户在前端勾选文件后,通过JavaScript的`downloadFileByForm`函数提交表单,将选定的文件路径发送到服务器进行打包下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
         * 批量下载
         * @param filepath
         * @param request
         * @param type
         * @throws IOException
         * @throws ServletException
         */

@RequestMapping(value = "downloads",method = RequestMethod.POST)

public void downloads(Uploading uploading ,String[] filepath,HttpServletRequest request,HttpServletResponse response,String name,String type) throws IOException, ServletException{

            Date day=new Date();
            SimpleDateFormat df = new SimpleDateFormat("HHmmss");
            // 要生成的压缩文件地址和文件名称
            String path=request.getSession().getServletContext().getRealPath("/file/"+type+"/"+name+df.format(day)+".zip");
            File zipFile = new File(path);
            ZipOutputStream zipStream = null;
            FileInputStream zipSource = null;
            BufferedInputStream bufferStream = null;
            try {
                //构造最终压缩包的输出流
                zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
                for(int i =0;i<filepath.length;i++){
                    File file = new File(request.getSession().getServletContext().getRealPath("/")+"file/"+type+"/"+filepath[i].substring(filepath[i].lastIndexOf("/")).substring(1));
                  //将需要压缩的文件格式化为输入流
                    zipSource = new FileInputStream(file);
                    //压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样
                    ZipEntry zipEntry = new ZipEntry(file.getName());
                    //定位该压缩条目位置,开始写入文件到压缩包中
                    zipStream.putNextEntry(zipEntry);
                 //输入缓冲流
                 bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
                 int read = 0;
                 //创建读写缓冲区
                 byte[] buf = new byte[1024 * 10];
                 while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1)
                {
                    zipStream.write(buf, 0, read);
                }
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                    //关闭流
                    try {
                        if(null != bufferStream) bufferStream.close();
                        if(null != zipStream) zipStream.close();
                        if(null != zipSource) zipSource.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
              //2.获取要下载的文件名
              String fileName = path.substring(path.lastIndexOf("\\")+1);
              //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
              File fi=new File(path);
              response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
              response.addHeader("Content-Length", "" + fi.length());
                response.setContentType("application/octet-stream");
              //4.获取要下载的文件输入流
              InputStream in = new FileInputStream(fi);
              int len = 0;
              //5.创建数据缓冲区
              byte[] buffer = new byte[1024];
              //6.通过response对象获取OutputStream流
              OutputStream out = response.getOutputStream();
              //7.将FileInputStream流写入到buffer缓冲区
              while ((len = in.read(buffer)) > 0) {
              //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
                  out.write(buffer,0,len);
              }
              in.close();

        }



jsp:


<div id="butn" class="Bottom15 col-xs-11 col-sm-11 col-md-11">
                        <table  class="table table-condensed">
                            <thead class="bule-head" >
                                <tr>
                                    <th><input type="checkbox" name="tree" id="query-btn"/>序号</th>
                                    <th>名称</th>
                                    <th class="text-center">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                             <form:form>
                             <c:forEach items="${file}" var="list">
                                <tr>
                                    <td><input type="checkbox" name="tree_id" value="${list.file}" /></td>
                                    <td>${list.fileName}</td>
                                    <td class="text-center">
                                    <a class="btn btn-blue marginR10" href="#" onclick="dow('${list.file}')">预览</a>
                                    </td>
                                </tr>
                             </c:forEach>
                            </form:form>
                            </tbody>
                        </table>
                        <input type="submit" class="btn btn-blue marginR10" value="下载" onclick="downloadFileByForm('${list.information.name}');" >

                    </div>



js: 

function downloadFileByForm(name) {
                var tree=document.getElementsByName("tree_id");
                 var i;
                 var arr = [],item;
                 for(i=0;i<tree.length;i++){
                     item = tree[i];
                     if(item.checked && item.value){
                         arr[i]=item.value;
                     }
                 }
                 arr = arr.filter(function(n){return n});
                var url = "${ctx}/upload/uploading/downloads";
                var form = $("<form></form>").attr("action", url).attr("method", "post");
                form.append($("<input></input>").attr("type", "hidden").attr("name", "filepath").attr("value", arr.join(',')));
                form.append($("<input></input>").attr("type", "hidden").attr("name", "name").attr("value", name));
                form.append($("<input></input>").attr("type", "hidden").attr("name", "type").attr("value", "diagnose"));
                form.appendTo('body').submit().remove();
            }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值