OssFileService.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package com.fdkankan.fyun.oss;
  2. import com.aliyun.oss.OSS;
  3. import com.aliyun.oss.model.*;
  4. import com.fdkankan.fyun.constant.FYunConstants;
  5. import com.fdkankan.fyun.constant.FYunTypeEnum;
  6. import com.fdkankan.fyun.face.AbstractFYunFileService;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  11. import org.springframework.stereotype.Component;
  12. import org.springframework.util.CollectionUtils;
  13. import org.springframework.util.ObjectUtils;
  14. import java.io.*;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17. import java.util.Map;
  18. import java.util.stream.Collectors;
  19. @Component
  20. @ConditionalOnProperty(name = "fyun.type", havingValue = "oss")
  21. public class OssFileService extends AbstractFYunFileService {
  22. private Logger log = LoggerFactory.getLogger(this.getClass().getName());
  23. @Autowired
  24. private OSS ossClient;
  25. @Override
  26. public String uploadFile(String bucket, byte[] data, String remoteFilePath) {
  27. try {
  28. ossClient.putObject(bucket, remoteFilePath, new ByteArrayInputStream(data));
  29. } catch (Exception e) {
  30. log.error("oss上传文件失败", e);
  31. e.printStackTrace();
  32. }
  33. return null;
  34. }
  35. @Override
  36. public String uploadFile(String bucket, String filePath, String remoteFilePath) {
  37. return uploadFile(bucket, filePath, remoteFilePath, null);
  38. }
  39. @Override
  40. public String uploadFile(String bucket, String filePath, String remoteFilePath, Map<String, String> headers) {
  41. try {
  42. File file = new File(filePath);
  43. if (!file.exists()) {
  44. log.error("要上传的文件不存在:" + filePath);
  45. return null;
  46. }
  47. ObjectMetadata metadata = new ObjectMetadata();
  48. if (filePath.contains(".jpg")) {
  49. metadata.setContentType("image/jpeg");
  50. }
  51. if (filePath.contains(".mp4")) {
  52. metadata.setContentType("video/mp4");
  53. }
  54. if (filePath.contains(".mp3")) {
  55. metadata.setContentType("audio/mp3");
  56. }
  57. if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(headers)) {
  58. for (Map.Entry<String, String> header : headers.entrySet()) {
  59. metadata.setHeader(header.getKey(), header.getValue());
  60. }
  61. }
  62. ossClient.putObject(bucket, remoteFilePath, new File(filePath), metadata);
  63. } catch (Exception e) {
  64. log.error("oss上传文件失败", e);
  65. e.printStackTrace();
  66. }
  67. return null;
  68. }
  69. @Override
  70. public String uploadFileByCommand(String bucket, String filePath, String remoteFilePath) {
  71. try {
  72. String optType = new File(filePath).isDirectory() ? "folder" : "file";
  73. String command = String.format(fYunConstants.UPLOAD_SH, bucket, filePath, remoteFilePath, FYunTypeEnum.OSS.code(), optType);
  74. log.info("开始上传文件, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  75. callshell(command);
  76. } catch (Exception e) {
  77. log.error("上传文件失败, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  78. e.printStackTrace();
  79. }
  80. return null;
  81. }
  82. @Override
  83. public void downloadFileByCommand(String bucket, String filePath, String remoteFilePath) {
  84. try {
  85. String optType = new File(filePath).isDirectory() ? "folder" : "file";
  86. String command = String.format(fYunConstants.DOWNLOAD_SH, bucket, remoteFilePath, filePath, FYunTypeEnum.OSS.code(), optType);
  87. log.info("开始上传文件, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  88. callshell(command);
  89. } catch (Exception e) {
  90. log.error("上传文件失败, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  91. e.printStackTrace();
  92. }
  93. }
  94. @Override
  95. public void deleteFile(String bucket, String remoteFilePath) throws IOException {
  96. try {
  97. ossClient.deleteObject(bucket, remoteFilePath);
  98. } catch (Exception e) {
  99. log.error("OSS删除文件失败,key=" + remoteFilePath);
  100. e.printStackTrace();
  101. }
  102. }
  103. @Override
  104. public void deleteFolder(String bucket, String remoteFolderPath) {
  105. try {
  106. List<String> remoteFiles = listRemoteFiles(bucket, remoteFolderPath);
  107. if (CollectionUtils.isEmpty(remoteFiles)) {
  108. return;
  109. }
  110. DeleteObjectsRequest request = new DeleteObjectsRequest(bucket);
  111. request.setKeys(remoteFiles);
  112. ossClient.deleteObjects(request);
  113. } catch (Exception e) {
  114. log.error("OSS删除文件失败,key=" + remoteFolderPath);
  115. e.printStackTrace();
  116. }
  117. }
  118. @Override
  119. public void uploadMulFiles(String bucket, Map<String, String> filepaths) {
  120. try {
  121. for (Map.Entry<String, String> entry : filepaths.entrySet()) {
  122. uploadFile(bucket, entry.getKey(), entry.getValue(), null);
  123. }
  124. } catch (Exception e) {
  125. log.error("OSS批量上传文件失败!");
  126. }
  127. }
  128. @Override
  129. public List<String> listRemoteFiles(String bucket, String sourcePath) {
  130. List<String> keyList = new ArrayList<>();
  131. try {
  132. boolean flag = true;
  133. String nextMaker = null;
  134. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket);
  135. //指定下一级文件
  136. listObjectsRequest.setPrefix(sourcePath);
  137. //设置分页的页容量
  138. listObjectsRequest.setMaxKeys(200);
  139. do {
  140. //获取下一页的起始点,它的下一项
  141. listObjectsRequest.setMarker(nextMaker);
  142. ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
  143. List<String> collect = objectListing.getObjectSummaries().parallelStream()
  144. .map(OSSObjectSummary::getKey).collect(Collectors.toList());
  145. if (!CollectionUtils.isEmpty(collect)) {
  146. keyList.addAll(collect);
  147. }
  148. nextMaker = objectListing.getNextMarker();
  149. //全部执行完后,为false
  150. flag = objectListing.isTruncated();
  151. } while (flag);
  152. } catch (Exception e) {
  153. log.error("获取文件列表失败,path=" + sourcePath, e);
  154. e.printStackTrace();
  155. }
  156. return keyList;
  157. }
  158. @Override
  159. public void copyFileBetweenBucket(String sourceBucketName, String sourcePath, String targetBucketName, String targetPath) {
  160. try {
  161. List<String> files = listRemoteFiles(sourceBucketName, sourcePath);
  162. if (ObjectUtils.isEmpty(files)) {
  163. log.error("源文件夹为空:{}", sourcePath);
  164. }
  165. files.stream().forEach(file -> {
  166. ossClient.copyObject(sourceBucketName, file, targetBucketName, file.replace(sourcePath, targetPath));
  167. });
  168. } catch (Exception e) {
  169. log.error("列举文件目录失败,key=" + sourcePath);
  170. }
  171. }
  172. @Override
  173. public void copyFilesBetweenBucket(String sourceBucketName, String targetBucketName, Map<String, String> pathMap) {
  174. if (ObjectUtils.isEmpty(pathMap)) {
  175. return;
  176. }
  177. try {
  178. for (Map.Entry<String, String> entry : pathMap.entrySet()) {
  179. copyFileBetweenBucket(sourceBucketName, entry.getKey(), targetBucketName, entry.getValue());
  180. }
  181. } catch (Exception e) {
  182. log.error("批量复制文件失败!");
  183. }
  184. }
  185. @Override
  186. public String getFileContent(String bucketName, String remoteFilePath) {
  187. try {
  188. OSSObject ossObject = ossClient.getObject(bucketName, remoteFilePath);
  189. InputStream objectContent = ossObject.getObjectContent();
  190. StringBuilder contentJson = new StringBuilder();
  191. try (BufferedReader reader = new BufferedReader(new InputStreamReader(objectContent))) {
  192. while (true) {
  193. String line = reader.readLine();
  194. if (line == null) break;
  195. contentJson.append(line);
  196. }
  197. } catch (IOException e) {
  198. log.error("读取scene.json文件流失败", e);
  199. }
  200. ossObject.close();
  201. return contentJson.toString();
  202. } catch (Exception e) {
  203. log.error("获取文件内容失败:{}", remoteFilePath);
  204. return null;
  205. }
  206. }
  207. @Override
  208. public boolean fileExist(String bucket, String objectName) {
  209. try {
  210. return ossClient.doesObjectExist(bucket, objectName);
  211. } catch (Exception e) {
  212. log.error("判断文件是否存在失败:{}", objectName);
  213. return false;
  214. }
  215. }
  216. @Override
  217. public void downloadFile(String bucket, String remoteFilePath, String localPath) {
  218. try {
  219. File localFile = new File(localPath);
  220. if (!localFile.getParentFile().exists()) {
  221. localFile.getParentFile().mkdirs();
  222. }
  223. if(localFile.isDirectory()){
  224. String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/")+1);
  225. log.info("未配置文件名,使用默认文件名:{}",fileName);
  226. localPath = localPath.concat(File.separator).concat(fileName);
  227. }
  228. DownloadFileRequest request = new DownloadFileRequest(bucket, remoteFilePath);
  229. request.setDownloadFile(localPath);
  230. // 默认5个任务并发下载
  231. request.setTaskNum(5);
  232. // 启动断点续传
  233. request.setEnableCheckpoint(true);
  234. ossClient.downloadFile(request);
  235. } catch (Throwable throwable) {
  236. log.error("文件下载失败:{}", remoteFilePath);
  237. throwable.printStackTrace();
  238. }
  239. }
  240. }