FileService.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. package com.oqpo.api.service;
  2. import com.oqpo.api.constant.ApiConstants;
  3. import com.oqpo.api.entity.oper.FileEntity;
  4. import com.oqpo.api.enums.SystemMessageCode;
  5. import com.oqpo.api.exception.GlobalException;
  6. import com.oqpo.api.mapper.FileMapper;
  7. import com.oqpo.api.model.FileModel;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.apache.commons.io.FilenameUtils;
  10. import org.apache.commons.net.ftp.FTP;
  11. import org.apache.commons.net.ftp.FTPClient;
  12. import org.apache.commons.net.ftp.FTPReply;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.beans.factory.annotation.Value;
  15. import org.springframework.stereotype.Service;
  16. import org.springframework.util.FileCopyUtils;
  17. import org.springframework.web.multipart.MultipartFile;
  18. import javax.servlet.http.HttpServletRequest;
  19. import javax.servlet.http.HttpServletResponse;
  20. import java.io.*;
  21. import java.net.URLEncoder;
  22. import java.text.DecimalFormat;
  23. import java.util.List;
  24. import java.util.UUID;
  25. @Slf4j
  26. @Service
  27. public class FileService extends CommonService {
  28. @Autowired
  29. private FileMapper fileMapper;
  30. @Value("${ftp.path}")
  31. String ftpPath;
  32. @Value("${ftp.host}")
  33. String ftpHost;
  34. @Value("${ftp.port}")
  35. Integer ftpPort;
  36. @Value("${ftp.user}")
  37. String ftpUser;
  38. @Value("${ftp.pass}")
  39. String ftpPass;
  40. @Value("${ftp.domain}")
  41. String ftpDomain;
  42. @Value("${file.domain.url}")
  43. String domainUrl;
  44. @Value("${file.upload.path}")
  45. String uploadPath;
  46. @Value("${file.upload.folder}")
  47. String uploadFolder;
  48. public FileEntity fileUpload(String userId, String fileNo, String path, MultipartFile multipartFile) throws Exception {
  49. FileModel fileModel = new FileModel();
  50. FTPClient client = new FTPClient();
  51. try {
  52. if ((ApiConstants.FILE_MAX * (1024*1024*100)) < multipartFile.getSize()) {
  53. throw new GlobalException(SystemMessageCode.FILE_CAPACITY_FAIL);
  54. }
  55. client.setControlEncoding("UTF-8");
  56. client.connect(ftpHost, ftpPort);
  57. int resultCode = client.getReplyCode();
  58. if (!FTPReply.isPositiveCompletion(resultCode)) {
  59. System.out.println("FTP server refused connection.!");
  60. return null;
  61. } else {
  62. client.setSoTimeout(1000);
  63. if (!client.login(ftpUser, ftpPass)) {
  64. System.out.println("Login Error!");
  65. return null;
  66. }
  67. }
  68. String orgFileName = multipartFile.getOriginalFilename();
  69. String extension = FilenameUtils.getExtension(orgFileName);
  70. String fileName = UUID.randomUUID().toString() + "." + extension;
  71. String savePath = uploadPath + "/" + fileName;
  72. String remotePath = ftpPath + uploadFolder + "/" + path + "/" + fileName;
  73. String downUrl = ftpDomain + uploadFolder + "/" + path + "/" + fileName;
  74. File file = new File(savePath);
  75. file.getParentFile().mkdirs();
  76. multipartFile.transferTo(file);
  77. FileInputStream inputStream = new FileInputStream(file);
  78. client.enterLocalPassiveMode();
  79. client.makeDirectory(ftpPath + uploadFolder + "/" + path);
  80. client.setFileType(FTP.BINARY_FILE_TYPE);
  81. client.storeFile(remotePath, inputStream);
  82. inputStream.close();
  83. deleteFolder(uploadPath);
  84. fileModel.setFileNo(fileNo);
  85. fileModel.setFileName(fileName);
  86. fileModel.setFileOrgName(orgFileName);
  87. fileModel.setDomainUrl(downUrl);
  88. fileModel.setFilePath(path);
  89. fileModel.setExtension(extension);
  90. fileModel.setFileSize(byteCalculation(multipartFile.getSize()));
  91. return saveFile(userId, fileModel);
  92. } catch (GlobalException e) {
  93. throw new GlobalException(e.getSystemMessageCode());
  94. } catch (Exception e) {
  95. e.printStackTrace();
  96. throw new GlobalException(SystemMessageCode.FILE_ERR);
  97. } finally {
  98. try {
  99. if (client.isConnected()) {
  100. client.logout();
  101. client.disconnect();
  102. }
  103. } catch (Throwable e) {
  104. e.printStackTrace();
  105. }
  106. }
  107. }
  108. public FileEntity saveFile(String userId, FileModel fileModel) {
  109. String fileNo = fileModel.getFileNo();
  110. if (fileNo.trim().equals("")) {
  111. fileNo = this.fnGetKeyNo(1);
  112. }
  113. String filePath = domainUrl + uploadFolder + "/" + fileModel.getFilePath() + "/" + fileModel.getFileName();
  114. FileEntity fileEntity = new FileEntity();
  115. fileEntity.setFileNo(fileNo);
  116. fileEntity.setFileOrgNm(fileModel.getFileOrgName());
  117. fileEntity.setFileNm(fileModel.getFileName());
  118. fileEntity.setFilePath(filePath);
  119. fileEntity.setFileType(fileModel.getFilePath());
  120. fileEntity.setFileSize(fileModel.getFileSize());
  121. fileEntity.setAddId(userId);
  122. fileMapper.insertFile(fileEntity);
  123. return fileEntity;
  124. }
  125. public List<FileEntity> fileList(String fileNo) throws Exception {
  126. return fileMapper.selectFileList(fileNo);
  127. }
  128. public void fileDelete(String fileNo, Integer fileSeq) {
  129. fileMapper.deleteFile(fileNo, fileSeq);
  130. }
  131. public void fileDownload(String fileNo, Integer fileSeq, HttpServletRequest request, HttpServletResponse response) throws Exception {
  132. FileModel fileModel = new FileModel();
  133. FTPClient client = new FTPClient();
  134. try {
  135. FileEntity entity = fileMapper.selectFile(fileNo, fileSeq);
  136. if (entity == null) {
  137. throw new GlobalException(SystemMessageCode.FILE_DOWN_ERR);
  138. }
  139. String filePath = ftpPath + uploadFolder + "/" + entity.getFileType() + "/";
  140. String fileName = entity.getFileNm();
  141. client.setControlEncoding("UTF-8");
  142. client.connect(ftpHost, ftpPort);
  143. int resultCode = client.getReplyCode();
  144. if (!FTPReply.isPositiveCompletion(resultCode)) {
  145. System.out.println("FTP server refused connection.!");
  146. } else {
  147. client.setSoTimeout(1000);
  148. if (!client.login(ftpUser, ftpPass)) {
  149. System.out.println("Login Error!");
  150. }
  151. }
  152. File file = new File(uploadPath);
  153. file.mkdirs();
  154. FileOutputStream fo = new FileOutputStream(uploadPath + fileName);
  155. client.enterLocalPassiveMode();
  156. client.setFileType(FTP.BINARY_FILE_TYPE);
  157. if (client.retrieveFile(filePath + fileName, fo)) {
  158. System.out.println("Download - Success");
  159. }
  160. fo.close();
  161. fileModel.setFilePath(uploadPath + fileName);
  162. File attachFile = new File(fileModel.getFilePath());
  163. if (attachFile.exists() && attachFile.isFile()) {
  164. response.setContentType("application/octet-stream; charset=utf-8");
  165. response.setContentLength((int) attachFile.length());
  166. String browser = getBrowser(request);
  167. String disposition = getDisposition(entity.getFileOrgNm(), browser);
  168. response.setHeader("Content-Disposition", disposition);
  169. response.setHeader("Content-Transfer-Encoding", "binary");
  170. OutputStream out = response.getOutputStream();
  171. FileInputStream fis = null;
  172. fis = new FileInputStream(attachFile);
  173. FileCopyUtils.copy(fis, out);
  174. if (fis != null) fis.close();
  175. out.flush();
  176. out.close();
  177. } else {
  178. throw new GlobalException(SystemMessageCode.FILE_DOWN_ERR);
  179. }
  180. } catch (Exception e) {
  181. e.printStackTrace();
  182. throw new GlobalException(SystemMessageCode.FILE_DOWN_ERR);
  183. } finally {
  184. try {
  185. deleteFolder(uploadPath);
  186. if (client.isConnected()) {
  187. client.logout();
  188. client.disconnect();
  189. }
  190. } catch (Throwable e) {
  191. e.printStackTrace();
  192. }
  193. }
  194. }
  195. public void deleteFolder(String delPath) {
  196. File folder = new File(delPath);
  197. File[] folderList = folder.listFiles();
  198. for (int i = 0; i < folderList.length; i++) {
  199. if (folderList[i].isFile()) {
  200. folderList[i].delete();
  201. } else {
  202. deleteFolder(folderList[i].getPath());
  203. }
  204. folderList[i].delete();
  205. }
  206. folder.delete();
  207. }
  208. public String byteCalculation(Long bytes) {
  209. String retFormat = "0";
  210. String[] s = { "bytes", "KB", "MB", "GB", "TB", "PB" };
  211. if (bytes != 0) {
  212. int idx = (int) Math.floor(Math.log(bytes) / Math.log(1024));
  213. DecimalFormat df = new DecimalFormat("#,###.##");
  214. double ret = ((bytes / Math.pow(1024, Math.floor(idx))));
  215. retFormat = df.format(ret) + " " + s[idx];
  216. } else {
  217. retFormat += " " + s[0];
  218. }
  219. return retFormat;
  220. }
  221. public String getBrowser(HttpServletRequest request) {
  222. String header = request.getHeader("User-Agent");
  223. if (header.indexOf("MSIE") > -1 || header.indexOf("Trident") > -1)
  224. return "MSIE";
  225. else if (header.indexOf("Chrome") > -1)
  226. return "Chrome";
  227. else if (header.indexOf("Opera") > -1)
  228. return "Opera";
  229. return "Firefox";
  230. }
  231. public String getDisposition(String filename, String browser) throws UnsupportedEncodingException {
  232. String dispositionPrefix = "attachment;filename=";
  233. String encodedFilename = null;
  234. if (browser.equals("MSIE")) {
  235. encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
  236. } else if (browser.equals("Firefox")) {
  237. encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
  238. } else if (browser.equals("Opera")) {
  239. encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
  240. } else if (browser.equals("Chrome")) {
  241. StringBuffer sb = new StringBuffer();
  242. for (int i = 0; i < filename.length(); i++) {
  243. char c = filename.charAt(i);
  244. if (c > '~') {
  245. sb.append(URLEncoder.encode("" + c, "UTF-8"));
  246. } else {
  247. sb.append(c);
  248. }
  249. }
  250. encodedFilename = sb.toString();
  251. }
  252. return dispositionPrefix + encodedFilename;
  253. }
  254. }