OssFileService.java 9.6 KB

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