废话不多说,直接上代码(Vue + java)

Vue前段代码

// 此处是触发下载功能的函数
	downFileToZip() {
		  let urls = 'fileUrl1,fileUrl2,fileUrl3'    //设置参数
		  let downUrl = 'localhost:8080/test/down?params=' + urls     //设置请求地址,拼接参数
	      // 注意请求方式,不可以采用ajax方法
	      window.location.href = downUrl
	}

Java后端代码

@GetMapping("down")
    public void batchDown(@RequestParam String params, HttpServletResponse response) {
    	//判断参数是否有效
        if (null == params || StrUtil.isEmpty(params) || params.split(",").length == 0) return;
        String[] urls= params.split(",");   
       try {
       		//设置下载的文件名称, 注意中文名需要做编码类型转换
            String filename = ValuesUtils.getString(System.currentTimeMillis() + ".zip");
            response.setContentType("application/x-octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName="+filename);
            response.setCharacterEncoding("utf-8");
            //创建zip输出流
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            byte[] buffer = new byte[1024];
            BufferedInputStream bufferStream = null;
            int index = 1;
            for (String url: urls) {
            		//设置zip里面每个文件的名称
                    zos.putNextEntry(new ZipEntry("文件名" + index + ".pdf"));
                    //根据文件地址获取输入流
                    InputStream is = new URL(url).openConnection().getInputStream();
                    int length;
                    while ((length = is.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }
                    is.close();
                    index ++;
            }
            //关流代码最好是写在finally{}代码块中,这里做测试就偷个懒
            zos.closeEntry();
            zos.close();
            zos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Logo

前往低代码交流专区

更多推荐