本文共 2742 字,大约阅读时间需要 9 分钟。
@RequestMapping(value = "/downDir", method = {RequestMethod.POST, RequestMethod.GET}) public ResponseEntitydownDir(@RequestParam("dirPath") String dirPath, HttpServletRequest request) throws Exception { HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); // 指定返回的zip文件名,这里就直接用时间戳了,可以自己选择 headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".zip"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); headers.add("Last-Modified", new Date().toString()); headers.add("ETag", String.valueOf(System.currentTimeMillis())); ByteArrayOutputStream zos = downloadDirectory(dirPath); byte[] out = zos.toByteArray(); zos.close(); ResponseEntity response = new ResponseEntity<>(out, headers, HttpStatus.OK); return response; } //压缩目录 public void compress(String dirPath, ZipOutputStream zipOutputStream, FileSystem fs) throws IOException { // 要下载的目录dirPath FileStatus[] fileStatulist = fs.listStatus(new Path(dirPath)); for (int i = 0; i < fileStatulist.length; i++) { String fileName = fileStatulist[i].getPath().getName(); if (fileStatulist[i].isFile()) { Path path = fileStatulist[i].getPath(); FSDataInputStream inputStream = fs.open(path); zipOutputStream.putNextEntry(new ZipEntry(fileName)); IOUtils.copyBytes(inputStream, zipOutputStream, 1024); inputStream.close(); } else { zipOutputStream.putNextEntry(new ZipEntry(fileName+ "/"));//因为是目录,所以加上/ 就会自动分层 // 这里的substring是因为这个返回的是hdfs://192.168.1.100:9000XXXXX/xxx/xx一大堆, // 而我们要的是/data/img类似这样的目录。 compress(fileStatulist[i].getPath().toString().substring(25), zipOutputStream, fs); } } } //下载一个目录 public ByteArrayOutputStream downloadDirectory(String dirPath) throws IOException, InterruptedException, URISyntaxException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://192.168.1.100:9000"), conf, "hadoop"); ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(out); compress(dirPath, zos, fs); zos.close(); return out; }
其中还遇到一些问题,由于流没有关闭,导致下载的zip文件解压的时候是损坏的。所以流记得关很重要。
参考
https://blog.csdn.net/u010366748/article/details/78615004 https://blog.csdn.net/qq_33872191/article/details/84977588 https://blog.csdn.net/liu16659/article/details/79200775 https://www.cnblogs.com/walker-/p/9768834.html https://blog.csdn.net/qq_41848006/article/details/85786908