public static void downFile(String host, int port, String username, String password, String remotePath, MerchantFile merchantFile, HttpServletResponse response) throws Exception { FTPClient ftp = null; List<byte[]> listBytes = new ArrayList<>(); String[] ftpFileNames = merchantFile.getFtpFileName().split(","); for (String ftpFileName : ftpFileNames){ try { ftp = new FTPClient(); log.info("开始进入多文件下载:" + merchantFile.getFileName()); //3、定义返回的状态码 int reply; //4、连接ftp(当前项目所部署的服务器和ftp服务器之间可以相互通讯,表示连接成功) ftp.connect(host, port); //5、输入账号和密码进行登录 ftp.login(username, password); //6、接受状态码(如果成功,返回230,如果失败返回503) reply = ftp.getReplyCode(); //7、根据状态码检测ftp的连接,调用isPositiveCompletion(reply)-->如果连接成功返回true,否则返回false log.info("FTP reply = {}",reply); if (!FTPReply.isPositiveCompletion(reply)) { log.error("FTP连接失败,需要断开连接!"); //说明连接失败,需要断开连接 ftp.disconnect(); } log.info("FTP连接成功!ftpFileName = {}", merchantFile.getFtpFileName()); // 转移到FTP服务器目录 log.info("开始下载!remotePath = {}", remotePath); boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath); if (!changeWorkingDirectory) { log.error("进入文件夹" + remotePath + "失败!"); } //设置为被动模式 ftp.enterLocalPassiveMode(); FTPFile[] fs = ftp.listFiles(); if (fs == null) { log.error(merchantFile.getFtpFileName() + ",文件为空!"); return; } else { log.info("开始下载!查找文件!!!" + fs.length); } log.info("文件名称= {}", ftpFileName); for (FTPFile ff : fs) { if (ff.getName().equals(ftpFileName)) { InputStream is = ftp.retrieveFileStream(ftpFileName); if (is != null) { log.info("文件大小 = {}", is.available()); byte[] down = IOUtils.toByteArray(is); listBytes.add(down); break; } } } }catch (Exception e){ log.error("FTP读取文件异常!", e); }finally{ disconnect(ftp); } } log.info("找到文件开始下载!"); String newName = URLEncoder.encode(merchantFile.getFileName(), StandardCharsets.UTF_8.toString()); // 设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString()); // 设置文件头:最后一个参数是设置下载的文件名并编码为UTF-8 response.setHeader("Content-Disposition", "attachment; filename=\"" + newName + "\"; filename*=utf-8''" + newName); // ftp文件获取文件 try { ZipOutputStream out = new ZipOutputStream(response.getOutputStream()); ByteArrayOutputStream fileOutputStream = new ByteArrayOutputStream(); ZipEntry entry = null; for (int i = 0; i < ftpFileNames.length; i++) { byte[] tmpBytes = listBytes.get(i); String name = ftpFileNames[i]; entry = new ZipEntry(name); // 存储项信息到压缩文件 out.putNextEntry(entry); // 将文件的内容通过字节数组复制到压缩文件中 out.write(tmpBytes, 0, tmpBytes.length); out.closeEntry(); } out.close(); out.flush(); fileOutputStream.close(); log.info("下载完成!"); } catch (Exception e) { log.error("下载异常!", e); throw e; } }
获取多个文件ZIP压缩
最新推荐文章于 2023-07-18 12:35:37 发布