荣鑫后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

587 lines
17 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package com.gaotao.modules.ftp.util;
  2. import com.gaotao.common.utils.ConfigConstant;
  3. import com.gaotao.common.utils.R;
  4. import com.gaotao.common.utils.SpringContextUtils;
  5. import com.gaotao.modules.oss.cloud.CloudStorageConfig;
  6. import com.gaotao.modules.pda.utils.ResponseData;
  7. import com.gaotao.modules.sys.service.SysConfigService;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.apache.commons.lang3.StringUtils;
  10. import org.apache.commons.net.ftp.FTP;
  11. import org.apache.commons.net.ftp.FTPClient;
  12. import org.apache.commons.net.ftp.FTPFile;
  13. import org.apache.commons.net.ftp.FTPReply;
  14. import org.springframework.beans.factory.annotation.Value;
  15. import javax.servlet.http.HttpServletResponse;
  16. import java.io.*;
  17. import java.net.URLEncoder;
  18. /**
  19. *
  20. * @ClassName: FTPUtils
  21. * @Description: TODO(这里用一句话描述这个类的作用)
  22. * @author lirui
  23. * @date 2018年4月29日
  24. *
  25. */
  26. @Slf4j
  27. public class FTPUtils {
  28. private static String serverUrl = "192.168.1.84";
  29. @Value("${com.ftp.ftpPort}")
  30. private static int port = 21;
  31. private static String username = "ftpadmin";
  32. private static String password = "XJerp123";
  33. private static SysConfigService sysConfigService;
  34. private static CloudStorageConfig config;
  35. static {
  36. sysConfigService = (SysConfigService) SpringContextUtils.getBean("sysConfigService");
  37. //获取储配置信息
  38. config = sysConfigService.getConfigObject(ConfigConstant.FTP_CONFIG_KEY, CloudStorageConfig.class);
  39. }
  40. /**
  41. * @throws IOException
  42. * @Title: getFTPClient
  43. * @Description: 获取ftp链接
  44. * @author lirui
  45. * @date 2018年4月29日
  46. * @param @param serverUrl
  47. * @param @param username
  48. * @param @param passWord
  49. * @param @return 参数
  50. * @return FTPClient 返回类型
  51. * @throws
  52. */
  53. public static FTPClient getFTPClient() {
  54. FTPClient ftpClient = new FTPClient();
  55. try {
  56. ftpClient.connect(config.getFtpHost(), config.getFtpPort());
  57. ftpClient.login(config.getFtpUser(), config.getFtpPassword());
  58. int replay = ftpClient.getReplyCode();
  59. //状态码有误关闭链接
  60. if(!FTPReply.isPositiveCompletion(replay)){
  61. ftpClient.disconnect();
  62. log.info("ftp链接有误,状态码:"+replay);
  63. }
  64. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  65. } catch (IOException e) {
  66. log.info("ftp链接有误,错误信息:"+e.getMessage());
  67. e.printStackTrace();
  68. }
  69. return ftpClient;
  70. }
  71. /**
  72. * @throws IOException
  73. *
  74. * @Title: changeToDir
  75. * @Description: 切换工作目录
  76. * @author lirui
  77. * @date 2018年4月30日
  78. * @param @return 参数
  79. * @return boolean 返回类型
  80. * @throws
  81. */
  82. public static void changeToDir(FTPClient ftpClient,String path) throws IOException{
  83. // 中文转码
  84. path = new String(path.toString().getBytes("GBK"),"iso-8859-1");
  85. /*该部分为逐级创建*/
  86. String[] split = path.split("/");
  87. String newPath = "";
  88. for (String str : split) {
  89. if(StringUtils.isBlank(str)) {
  90. continue;
  91. }
  92. newPath = newPath + "/" + str;
  93. // 判断是否已有该文件夹
  94. if (!ftpClient.changeWorkingDirectory(newPath)) {
  95. boolean makeDirectory = ftpClient.makeDirectory(newPath);
  96. System.err.println(str + "创建:" + makeDirectory);
  97. }
  98. // 切换文件夹
  99. boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory(newPath);
  100. System.err.println(";切换:" + changeWorkingDirectory);
  101. }
  102. }
  103. /**
  104. * @throws IOException
  105. *
  106. * @Title: changeToParentDir
  107. * @Description: 切换到父级目录
  108. * @author lirui
  109. * @date 2018年4月29日
  110. * @param @return 参数
  111. * @return boolean 返回类型
  112. * @throws
  113. */
  114. public static void changeToParentDir(FTPClient ftpClient) throws IOException{
  115. ftpClient.changeToParentDirectory();
  116. }
  117. /**
  118. *
  119. * @Title: uploadFile
  120. * @Description: 上传文件
  121. * @author lirui
  122. * @date 2018年4月29日
  123. * @date 2018年4月30日
  124. * @return 参数
  125. * @return ResponseData 返回类型
  126. * @throws
  127. */
  128. public static R uploadFtpFile( File file){
  129. R r = new R();
  130. FTPClient ftpClient = getFTPClient();
  131. //判断链接是否关闭
  132. if(!ftpClient.isConnected()){
  133. log.info("ftp链接出错!链接已关闭!");
  134. r.error(300,"ftp链接出错!链接已关闭!");
  135. return r;
  136. }
  137. //上传操作
  138. FileInputStream fis = null;
  139. try {
  140. fis = new FileInputStream(file);
  141. ftpClient.setBufferSize(10000);
  142. //切换目录
  143. ftpClient.setControlEncoding("UTF-8");
  144. changeToDir(ftpClient, config.getFtpDir());
  145. boolean flag = ftpClient.storeFile(new String(file.getName().getBytes("gbk"), "iso-8859-1"), fis);
  146. if(!flag){
  147. log.info("ftp上传失败!");
  148. r.error(303,"ftp上传失败!");
  149. return r;
  150. }
  151. ftpClient.logout();
  152. r.ok("ftp上传成功!");
  153. r.put("url",config.getFtpDir()+"//"+file.getName());
  154. return r;
  155. } catch (FileNotFoundException e) {
  156. log.info("ftp上传出错!错误信息:"+e.getMessage());
  157. r.error(301,"ftp上传出错!错误信息:"+e.getMessage());
  158. e.printStackTrace();
  159. } catch (UnsupportedEncodingException e) {
  160. e.printStackTrace();
  161. } catch (IOException e) {
  162. e.printStackTrace();
  163. }finally {
  164. try {
  165. fis.close();
  166. ftpClient.disconnect();
  167. } catch (IOException e) {
  168. e.printStackTrace();
  169. }
  170. }
  171. return r;
  172. }
  173. /**
  174. *
  175. * @Title: getFtpFile
  176. * @Description: 下载文件
  177. * @author lirui
  178. * @date 2018年4月30日
  179. * @param serverUrl ftp路径
  180. * @param username 用户名
  181. * @param password 密码
  182. * @param path 当前目录
  183. * @param fileName 当前目录下下载的文件名称
  184. * @return 参数
  185. * @return File 返回类型
  186. * @throws
  187. */
  188. public static ResponseData downFtpFile(String serverUrl,String username,String password,String path,String fileName){
  189. ResponseData responseData = new ResponseData();
  190. FTPClient ftpClient = getFTPClient();
  191. //判断链接是否关闭
  192. if(!ftpClient.isConnected()){
  193. log.info("ftp链接出错!链接已关闭!");
  194. responseData.setCode("300");
  195. responseData.setMsg("链接出错!");
  196. return responseData;
  197. }
  198. //进入工作空间
  199. boolean flag = true;
  200. FileOutputStream fos = null;
  201. try {
  202. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  203. flag = ftpClient.changeWorkingDirectory("/");
  204. if(!flag){
  205. log.info("ftp链接出错!文件夹不存在!");
  206. responseData.setCode("300");
  207. responseData.setMsg("ftp链接出错!文件件不存在!");
  208. return responseData;
  209. }
  210. //获取当前目录下的所有文件名称
  211. ftpClient.sendCommand("OPTS UTF8 ON");
  212. FTPFile[] ftpFiles = ftpClient.listFiles();
  213. //文件存在是否存在的标记
  214. boolean isExist = false;
  215. //循环判断文件
  216. for(int i = 0; i<ftpFiles.length; i++){
  217. String temp_name = new String(ftpFiles[i].getName().getBytes("iso-8859-1"), "UTF-8");
  218. if(fileName.equals(temp_name)){
  219. isExist = true;
  220. File temp_file = new File(fileName);
  221. fos = new FileOutputStream(temp_file);
  222. ftpClient.retrieveFile(ftpFiles[i].getName(), fos);
  223. responseData.setObj(temp_file);
  224. ftpClient.logout();
  225. break;
  226. }
  227. }
  228. if(isExist){
  229. responseData.setCode("200");
  230. responseData.setMsg("ftp下载成功!");
  231. }else{
  232. responseData.setCode("301");
  233. responseData.setMsg("ftp下载失败!");
  234. }
  235. } catch (IOException e) {
  236. // TODO Auto-generated catch block
  237. e.printStackTrace();
  238. }finally {
  239. //关闭流和链接
  240. try {
  241. if(fos!=null){
  242. fos.close();
  243. }
  244. if(ftpClient!=null){
  245. ftpClient.disconnect();
  246. }
  247. } catch (IOException e) {
  248. // TODO Auto-generated catch block
  249. e.printStackTrace();
  250. }
  251. }
  252. return responseData;
  253. }
  254. /**
  255. *
  256. * @Title: delFile
  257. * @Description: 删除文件
  258. * @author lirui
  259. * @date 2018年4月30日
  260. * @param serverUrl ftp路径
  261. * @param username 用户名
  262. * @param password 密码
  263. * @param path 当前目录
  264. * @param fileName 当前目录下删除文件名称
  265. * @param @return 参数
  266. * @return ResponseData 返回类型
  267. * @throws
  268. */
  269. public static ResponseData delFtpFile(String serverUrl,String username,String password,String path,String fileName){
  270. ResponseData responseData = new ResponseData();
  271. FTPClient ftpClient = getFTPClient();
  272. //判断链接是否关闭
  273. if(!ftpClient.isConnected()){
  274. log.info("ftp链接出错!链接已关闭!");
  275. responseData.setCode("300");
  276. responseData.setMsg("链接出错!");
  277. return responseData;
  278. }
  279. //进入工作空间
  280. boolean flag = true;
  281. try {
  282. flag = ftpClient.changeWorkingDirectory(path);
  283. if(!flag){
  284. log.info("ftp链接出错!文件夹不存在!");
  285. responseData.setCode("300");
  286. responseData.setMsg("ftp链接出错!文件件不存在!");
  287. return responseData;
  288. }
  289. //获取当前目录下的所有文件名称
  290. ftpClient.sendCommand("OPTS UTF8 ON");
  291. FTPFile[] ftpFiles = ftpClient.listFiles();
  292. //文件存在是否存在的标记
  293. boolean delFlag = false;
  294. //循环判断文件
  295. for(int i = 0; i<ftpFiles.length; i++){
  296. String temp_name = new String(ftpFiles[i].getName().getBytes("iso-8859-1"), "UTF-8");
  297. if(fileName.equals(temp_name)){
  298. delFlag = ftpClient.deleteFile(ftpFiles[i].getName());
  299. ftpClient.logout();
  300. }
  301. }
  302. if(delFlag){
  303. responseData.setCode("200");
  304. responseData.setMsg("ftp文件删除成功!");
  305. }else{
  306. responseData.setCode("301");
  307. responseData.setMsg("文件不存在,请检查后再试!");
  308. }
  309. } catch (IOException e) {
  310. // TODO Auto-generated catch block
  311. e.printStackTrace();
  312. }finally {
  313. //关闭流和链接
  314. try {
  315. if(ftpClient!=null){
  316. ftpClient.disconnect();
  317. }
  318. } catch (IOException e) {
  319. // TODO Auto-generated catch block
  320. e.printStackTrace();
  321. }
  322. }
  323. return responseData;
  324. }
  325. /**
  326. *
  327. * @Title: delFtpDir
  328. * @Description: TODO(这里用一句话描述这个方法的作用)
  329. * @author lirui
  330. * @date 2018年4月30日
  331. * @param serverUrl ftp路径
  332. * @param username 用户名
  333. * @param password 密码
  334. * @param path 当前目录
  335. * @param dir 当当前目录下删除文件夹名称
  336. * @return 参数
  337. * @return ResponseData 返回类型
  338. * @throws
  339. */
  340. public static ResponseData delFtpDir(String serverUrl,String username,String password,String path,String dir){
  341. ResponseData responseData = new ResponseData();
  342. FTPClient ftpClient = getFTPClient();
  343. //判断链接是否关闭
  344. if(!ftpClient.isConnected()){
  345. log.info("ftp链接出错!链接已关闭!");
  346. responseData.setCode("300");
  347. responseData.setMsg("链接出错!");
  348. return responseData;
  349. }
  350. //进入工作空间
  351. boolean flag = true;
  352. try {
  353. flag = ftpClient.changeWorkingDirectory(path+"\\"+dir);
  354. if(!flag){
  355. log.info("ftp链接出错!文件夹不存在!");
  356. responseData.setCode("300");
  357. responseData.setMsg("ftp链接出错!文件件不存在!");
  358. return responseData;
  359. }
  360. //返回父级目录
  361. ftpClient.changeToParentDirectory();
  362. //删除文件夹
  363. boolean delFlag = ftpClient.removeDirectory(dir);
  364. if(delFlag){
  365. responseData.setCode("200");
  366. responseData.setMsg("ftp文件删除成功!");
  367. }else{
  368. responseData.setCode("301");
  369. responseData.setMsg("文件不存在,请检查后再试!");
  370. }
  371. } catch (IOException e) {
  372. // TODO Auto-generated catch block
  373. e.printStackTrace();
  374. }finally {
  375. //关闭流和链接
  376. try {
  377. if(ftpClient!=null){
  378. ftpClient.disconnect();
  379. }
  380. } catch (IOException e) {
  381. // TODO Auto-generated catch block
  382. e.printStackTrace();
  383. }
  384. }
  385. return responseData;
  386. }
  387. public static R downFtpFile( String path, String fileName, String newFileName, HttpServletResponse response){
  388. R r = new R();
  389. FTPClient ftpClient = getFTPClient();
  390. //判断链接是否关闭
  391. if(!ftpClient.isConnected()){
  392. log.info("ftp链接出错!链接已关闭!");
  393. r.put("msg" ,"ftp链接出错!");
  394. r.put("success", false);
  395. return r;
  396. }
  397. //进入工作空间
  398. boolean flag = true;
  399. try {
  400. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  401. if(path == null || "".equals(path)){
  402. path = "/";
  403. }
  404. String name=new String(path.getBytes("UTF-8"),"iso-8859-1");
  405. flag = ftpClient.changeWorkingDirectory(name);
  406. // flag = ftpClient.changeWorkingDirectory("/");
  407. if(!flag){
  408. log.info("ftp链接出错!文件夹不存在!");
  409. r.put("msg" ,"文件件不存在!");
  410. r.put("success", false);
  411. return r;
  412. }
  413. //获取当前目录下的所有文件名称
  414. ftpClient.sendCommand("OPTS UTF8 ON");
  415. FTPFile[] ftpFiles = ftpClient.listFiles();
  416. //文件存在是否存在的标记
  417. boolean isExist = false;
  418. //循环判断文件
  419. for(int i = 0; i<ftpFiles.length; i++){
  420. String temp_name = new String(ftpFiles[i].getName().getBytes("iso-8859-1"), "UTF-8");
  421. if(fileName.equals(temp_name)){
  422. log.info("文件开始下载!文件名称:"+fileName);
  423. isExist = true;
  424. InputStream fis = ftpClient.retrieveFileStream(ftpFiles[i].getName());
  425. byte[] buffer = new byte[fis.available()];
  426. // 清空response
  427. response.reset();
  428. if(newFileName != null && !"".equals(newFileName)){
  429. fileName = newFileName;
  430. }
  431. // 设置response的Header
  432. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
  433. response.addHeader("Content-Length", "" + ftpFiles[i].getSize());
  434. response.setContentType("application/octet-stream");
  435. response.setCharacterEncoding("UTF-8");
  436. OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
  437. int length;
  438. while((length=fis.read(buffer))>0){ //把文件流写到缓冲区里
  439. toClient.write(buffer,0,length);
  440. }
  441. toClient.write(buffer);
  442. toClient.flush();
  443. fis.close();
  444. toClient.close();
  445. log.info("文件下载完成!文件名称:"+fileName);
  446. break;
  447. }
  448. }
  449. ftpClient.completePendingCommand();
  450. if(isExist){
  451. r.put("msg" ,"ftp下载成功!");
  452. r.put("success", true);
  453. }else{
  454. r.put("msg" ,"ftp下载失败!");
  455. r.put("success", false);
  456. }
  457. } catch (IOException e) {
  458. log.info("ftp下载出错!错误信息:"+e.getMessage());
  459. // TODO Auto-generated catch block
  460. e.printStackTrace();
  461. }finally {
  462. //关闭流和链接
  463. try {
  464. // if(fos!=null){
  465. // fos.close();
  466. // }
  467. if(ftpClient!=null){
  468. ftpClient.logout();
  469. }
  470. } catch (IOException e) {
  471. log.info("关闭流和链接出错!错误信息:"+e.getMessage());
  472. e.printStackTrace();
  473. }
  474. }
  475. return r;
  476. }
  477. /**`
  478. * @Desc ftp文件下载
  479. * @param response
  480. * @param path
  481. * @param fileName
  482. */
  483. public static void downFile( HttpServletResponse response, String path, String fileName){
  484. FTPClient ftpClient = getFTPClient();
  485. //判断链接是否关闭
  486. if(!ftpClient.isConnected()){
  487. log.info("ftp链接出错!链接已关闭!");
  488. }
  489. //进入工作空间
  490. boolean flag = true;
  491. try {
  492. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  493. if(path == null || "".equals(path)){
  494. path = "/";
  495. }
  496. String name=new String(path.getBytes("UTF-8"),"iso-8859-1");
  497. flag = ftpClient.changeWorkingDirectory(name);
  498. if(!flag){
  499. log.info("ftp链接出错!文件夹不存在!");
  500. }
  501. //获取当前目录下的所有文件名称
  502. ftpClient.sendCommand("OPTS UTF8 ON");
  503. FTPFile[] ftpFiles = ftpClient.listFiles();
  504. //文件存在是否存在的标记
  505. boolean isExist = false;
  506. //循环判断文件
  507. for(int i = 0; i<ftpFiles.length; i++){
  508. String temp_name = new String(ftpFiles[i].getName().getBytes("iso-8859-1"), "UTF-8");
  509. if(fileName.equals(temp_name)){
  510. log.info("文件开始下载!文件名称:"+fileName);
  511. isExist = true;
  512. InputStream fis = ftpClient.retrieveFileStream(ftpFiles[i].getName());
  513. byte[] buffer = new byte[fis.available()];
  514. // 清空response
  515. response.reset();
  516. // 设置response的Header
  517. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
  518. response.addHeader("Content-Length", "" + ftpFiles[i].getSize());
  519. response.setContentType("application/octet-stream");
  520. response.setCharacterEncoding("UTF-8");
  521. OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
  522. int length;
  523. while((length=fis.read(buffer))>0){ //把文件流写到缓冲区里
  524. toClient.write(buffer,0,length);
  525. }
  526. toClient.write(buffer);
  527. toClient.flush();
  528. fis.close();
  529. toClient.close();
  530. ftpClient.completePendingCommand();
  531. log.info("下载完成!文件名称:"+fileName);
  532. }
  533. }
  534. ftpClient.completePendingCommand();
  535. if(isExist){
  536. log.info("下载完成!文件名称:"+fileName);
  537. }else{
  538. log.info("下载失败!文件名称:"+fileName);
  539. }
  540. } catch (IOException e) {
  541. log.info("ftp下载出错!错误信息:"+e.getMessage());
  542. // TODO Auto-generated catch block
  543. e.printStackTrace();
  544. }finally {
  545. //关闭流和链接
  546. try {
  547. if(ftpClient!=null){
  548. ftpClient.logout();
  549. }
  550. } catch (IOException e) {
  551. log.info("关闭流和链接出错!错误信息:"+e.getMessage());
  552. // TODO Auto-generated catch block
  553. e.printStackTrace();
  554. }
  555. }
  556. }
  557. // 本地盘直接读取
  558. public static void downFile1(String path, String fileName){
  559. String ipPath = config.getFtpDir()+fileName;
  560. File file = new File(ipPath);
  561. try {
  562. OutputStream os = new FileOutputStream(file);
  563. } catch (FileNotFoundException e) {
  564. e.printStackTrace();
  565. }
  566. }
  567. }