OssFileService.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. package com.fdkankan.fyun.oss;
  2. import com.aliyun.oss.HttpMethod;
  3. import com.aliyun.oss.OSS;
  4. import com.aliyun.oss.model.*;
  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.net.URL;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.stream.Collectors;
  20. @Component
  21. @ConditionalOnProperty(name = "fyun.type", havingValue = "oss")
  22. public class OssFileService extends AbstractFYunFileService {
  23. private Logger log = LoggerFactory.getLogger(this.getClass().getName());
  24. @Autowired
  25. private OSS ossClient;
  26. @Override
  27. public String uploadFile(String bucket, byte[] data, String remoteFilePath) {
  28. try {
  29. ossClient.putObject(bucket, remoteFilePath, new ByteArrayInputStream(data));
  30. } catch (Exception e) {
  31. log.error("oss上传文件失败,remoteFilePath:" + remoteFilePath, e);
  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, InputStream inputStream, String remoteFilePath) {
  41. try {
  42. ossClient.putObject(bucket, remoteFilePath, inputStream);
  43. log.info("文件流上传成功,目标路径:remoteFilePath:{}", remoteFilePath);
  44. } catch (Exception e) {
  45. log.error("oss上传文件失败,remoteFilePath:"+remoteFilePath, e);
  46. }
  47. return null;
  48. }
  49. @Override
  50. public String uploadFile(String bucket, String filePath, String remoteFilePath, Map<String, String> headers) {
  51. try {
  52. File file = new File(filePath);
  53. if (!file.exists()) {
  54. log.warn("要上传的文件不存在,filePath" + filePath);
  55. return null;
  56. }
  57. ObjectMetadata metadata = new ObjectMetadata();
  58. if (filePath.contains(".jpg")) {
  59. metadata.setContentType("image/jpeg");
  60. }
  61. if (filePath.contains(".mp4")) {
  62. metadata.setContentType("video/mp4");
  63. }
  64. if (filePath.contains(".mp3")) {
  65. metadata.setContentType("audio/mp3");
  66. }
  67. if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(headers)) {
  68. for (Map.Entry<String, String> header : headers.entrySet()) {
  69. metadata.setHeader(header.getKey(), header.getValue());
  70. }
  71. }
  72. ossClient.putObject(bucket, remoteFilePath, file, metadata);
  73. log.info("文件上传成功,path:{}", filePath);
  74. } catch (Exception e) {
  75. log.error("oss上传文件失败,filePath:"+filePath, e);
  76. }
  77. return null;
  78. }
  79. @Override
  80. public String uploadFileByCommand(String bucket, String filePath, String remoteFilePath) {
  81. try {
  82. String optType = new File(filePath).isDirectory() ? "folder" : "file";
  83. String command = String.format(fYunConstants.UPLOAD_SH, bucket, filePath, remoteFilePath, FYunTypeEnum.OSS.code(), optType);
  84. log.info("开始上传文件, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  85. callshell(command);
  86. log.info("上传文件完毕, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  87. } catch (Exception e) {
  88. log.error(String.format("上传文件失败, ossPath:%s, srcPath:%s", remoteFilePath, filePath), e);
  89. }
  90. return null;
  91. }
  92. @Override
  93. public void downloadFileByCommand(String bucket, String filePath, String remoteFilePath) {
  94. try {
  95. String optType = remoteFilePath.contains(".") ? "file" : "folder";
  96. String command = String.format(fYunConstants.DOWNLOAD_SH, bucket, remoteFilePath, filePath, FYunTypeEnum.OSS.code(), optType);
  97. log.info("开始下载文件, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  98. callshell(command);
  99. log.info("下载文件完毕, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  100. } catch (Exception e) {
  101. log.error(String.format("下载文件失败, ossPath:%s, srcPath:%s", remoteFilePath, filePath), e);
  102. }
  103. }
  104. @Override
  105. public void deleteFile(String bucket, String remoteFilePath) throws IOException {
  106. try {
  107. ossClient.deleteObject(bucket, remoteFilePath);
  108. } catch (Exception e) {
  109. log.error("OSS删除文件失败,key:" + remoteFilePath, e);
  110. }
  111. }
  112. @Override
  113. public void deleteFolder(String bucket, String remoteFolderPath) {
  114. try {
  115. if (!remoteFolderPath.endsWith(File.separator)) {
  116. remoteFolderPath = remoteFolderPath + File.separator;
  117. }
  118. boolean flag = true;
  119. String nextMaker = null;
  120. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket).withPrefix(remoteFolderPath).withMaxKeys(1000);
  121. DeleteObjectsRequest request = new DeleteObjectsRequest(bucket);
  122. do {
  123. //获取下一页的起始点,它的下一项
  124. listObjectsRequest.setMarker(nextMaker);
  125. ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
  126. List<String> keys = objectListing.getObjectSummaries().parallelStream()
  127. .map(OSSObjectSummary::getKey).collect(Collectors.toList());
  128. if (!CollectionUtils.isEmpty(keys)) {
  129. request.setKeys(keys);
  130. ossClient.deleteObjects(request);
  131. }
  132. nextMaker = objectListing.getNextMarker();
  133. //全部执行完后,为false
  134. flag = objectListing.isTruncated();
  135. } while (flag);
  136. } catch (Exception e) {
  137. log.error("OSS删除文件失败,key:" + remoteFolderPath, e);
  138. }
  139. }
  140. @Override
  141. public void uploadMulFiles(String bucket, Map<String, String> filepaths) {
  142. try {
  143. for (Map.Entry<String, String> entry : filepaths.entrySet()) {
  144. uploadFile(bucket, entry.getKey(), entry.getValue(), null);
  145. }
  146. } catch (Exception e) {
  147. log.error("OSS批量上传文件失败!");
  148. }
  149. }
  150. @Override
  151. public List<String> listRemoteFiles(String bucket, String sourcePath) {
  152. List<String> keyList = new ArrayList<>();
  153. try {
  154. boolean flag = true;
  155. String nextMaker = null;
  156. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket);
  157. //指定下一级文件
  158. listObjectsRequest.setPrefix(sourcePath);
  159. //设置分页的页容量
  160. listObjectsRequest.setMaxKeys(200);
  161. do {
  162. //获取下一页的起始点,它的下一项
  163. listObjectsRequest.setMarker(nextMaker);
  164. ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
  165. List<String> collect = objectListing.getObjectSummaries().parallelStream()
  166. .map(OSSObjectSummary::getKey).collect(Collectors.toList());
  167. if (!CollectionUtils.isEmpty(collect)) {
  168. keyList.addAll(collect);
  169. }
  170. nextMaker = objectListing.getNextMarker();
  171. //全部执行完后,为false
  172. flag = objectListing.isTruncated();
  173. } while (flag);
  174. } catch (Exception e) {
  175. log.error("获取文件列表失败,path:" + sourcePath, e);
  176. }
  177. return keyList;
  178. }
  179. @Override
  180. public void copyFileBetweenBucket(String sourceBucketName, String sourcePath, String targetBucketName, String targetPath) {
  181. try {
  182. List<String> files = listRemoteFiles(sourceBucketName, sourcePath);
  183. if (ObjectUtils.isEmpty(files)) {
  184. return;
  185. }
  186. files.stream().forEach(file -> {
  187. ossClient.copyObject(sourceBucketName, file, targetBucketName, file.replace(sourcePath, targetPath));
  188. });
  189. } catch (Exception e) {
  190. log.error("列举文件目录失败,key:" + sourcePath, e);
  191. }
  192. }
  193. @Override
  194. public void copyFilesBetweenBucket(String sourceBucketName, String targetBucketName, Map<String, String> pathMap) {
  195. if (ObjectUtils.isEmpty(pathMap)) {
  196. return;
  197. }
  198. try {
  199. for (Map.Entry<String, String> entry : pathMap.entrySet()) {
  200. copyFileBetweenBucket(sourceBucketName, entry.getKey(), targetBucketName, entry.getValue());
  201. }
  202. } catch (Exception e) {
  203. log.error(String.format("批量复制文件失败, sourceBucketName:%s, targetBucketName:%s", sourceBucketName, targetBucketName), e);
  204. }
  205. }
  206. @Override
  207. public String getFileContent(String bucketName, String remoteFilePath) {
  208. try (OSSObject ossObject = ossClient.getObject(bucketName, remoteFilePath)){
  209. InputStream objectContent = ossObject.getObjectContent();
  210. StringBuilder contentJson = new StringBuilder();
  211. try (BufferedReader reader = new BufferedReader(new InputStreamReader(objectContent))) {
  212. while (true) {
  213. String line = reader.readLine();
  214. if (line == null) break;
  215. contentJson.append(line);
  216. }
  217. } catch (IOException e) {
  218. throw e;
  219. }
  220. return contentJson.toString();
  221. } catch (Exception e) {
  222. log.error("获取文件内容失败:key:"+remoteFilePath, e);
  223. }
  224. return null;
  225. }
  226. @Override
  227. public boolean fileExist(String bucket, String objectName) {
  228. try {
  229. return ossClient.doesObjectExist(bucket, objectName);
  230. } catch (Exception e) {
  231. log.error("判断文件是否存在失败,key:"+objectName, e);
  232. }
  233. return false;
  234. }
  235. @Override
  236. public void downloadFile(String bucket, String remoteFilePath, String localPath) {
  237. try {
  238. File localFile = new File(localPath);
  239. if (!localFile.getParentFile().exists()) {
  240. localFile.getParentFile().mkdirs();
  241. }
  242. if(localFile.isDirectory()){
  243. String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/")+1);
  244. log.info("未配置文件名,使用默认文件名:{}",fileName);
  245. localPath = localPath.concat(File.separator).concat(fileName);
  246. }
  247. DownloadFileRequest request = new DownloadFileRequest(bucket, remoteFilePath);
  248. request.setDownloadFile(localPath);
  249. // 默认5个任务并发下载
  250. request.setTaskNum(5);
  251. // 启动断点续传
  252. request.setEnableCheckpoint(true);
  253. ossClient.downloadFile(request);
  254. } catch (Throwable throwable) {
  255. log.error("文件下载失败,key:"+remoteFilePath, throwable);
  256. }
  257. }
  258. @Override
  259. public URL getPresignedUrl(String bucket, String url) {
  260. java.util.Date expiration = new java.util.Date();
  261. long expTimeMillis = expiration.getTime();
  262. expTimeMillis += 1000 * 60 * 60 * 8;
  263. expiration.setTime(expTimeMillis);
  264. GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket, url);
  265. generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
  266. generatePresignedUrlRequest.setExpiration(expiration);
  267. return ossClient.generatePresignedUrl(generatePresignedUrlRequest);
  268. }
  269. @Override
  270. public long getSubFileNums(String bucket, String url) {
  271. long totalSubFileNum = 0;
  272. try {
  273. boolean flag = true;
  274. String nextMaker = null;
  275. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket);
  276. //指定下一级文件
  277. listObjectsRequest.setPrefix(url);
  278. //设置分页的页容量
  279. listObjectsRequest.setMaxKeys(200);
  280. do {
  281. //获取下一页的起始点,它的下一项
  282. listObjectsRequest.setMarker(nextMaker);
  283. ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
  284. List<String> collect = objectListing.getObjectSummaries().parallelStream()
  285. .map(OSSObjectSummary::getKey).collect(Collectors.toList());
  286. if (!CollectionUtils.isEmpty(collect)) {
  287. totalSubFileNum = totalSubFileNum + collect.size();
  288. }
  289. nextMaker = objectListing.getNextMarker();
  290. //全部执行完后,为false
  291. flag = objectListing.isTruncated();
  292. } while (flag);
  293. } catch (Exception e) {
  294. log.error("获取文件数量失败,path:" + url, e);
  295. }
  296. return totalSubFileNum;
  297. }
  298. }