UploadToOssUtil.java 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. package com.fdkankan.fyun.oss;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.io.FileUtil;
  4. import com.aliyun.oss.OSSClient;
  5. import com.aliyun.oss.model.DeleteObjectsRequest;
  6. import com.aliyun.oss.model.DeleteObjectsResult;
  7. import com.aliyun.oss.model.ListObjectsRequest;
  8. import com.aliyun.oss.model.ObjectListing;
  9. import com.aliyun.oss.model.ObjectMetadata;
  10. import com.aliyun.oss.model.PutObjectResult;
  11. import com.aliyun.oss.model.*;
  12. import com.amazonaws.HttpMethod;
  13. import com.amazonaws.auth.AWSStaticCredentialsProvider;
  14. import com.amazonaws.auth.BasicAWSCredentials;
  15. import com.amazonaws.regions.Regions;
  16. import com.amazonaws.services.s3.AmazonS3;
  17. import com.amazonaws.services.s3.AmazonS3ClientBuilder;
  18. import com.amazonaws.services.s3.model.CannedAccessControlList;
  19. import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion;
  20. import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
  21. import com.amazonaws.services.s3.model.GetObjectRequest;
  22. import com.amazonaws.services.s3.model.PutObjectRequest;
  23. import com.amazonaws.services.s3.model.*;
  24. import com.fdkankan.fyun.constant.StorageType;
  25. import com.fdkankan.fyun.model.StreamGobbler;
  26. import lombok.extern.slf4j.Slf4j;
  27. import org.apache.commons.fileupload.FileItem;
  28. import org.apache.commons.fileupload.FileItemFactory;
  29. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  30. import org.apache.commons.io.FileUtils;
  31. import org.apache.commons.lang3.StringUtils;
  32. import org.springframework.beans.factory.annotation.Value;
  33. import org.springframework.stereotype.Component;
  34. import org.springframework.web.multipart.MultipartFile;
  35. import org.springframework.web.multipart.commons.CommonsMultipartFile;
  36. import java.io.*;
  37. import java.net.FileNameMap;
  38. import java.net.URL;
  39. import java.net.URLConnection;
  40. import java.net.URLDecoder;
  41. import java.util.ArrayList;
  42. import java.util.HashMap;
  43. import java.util.List;
  44. import java.util.Map;
  45. import java.util.stream.Collectors;
  46. @Slf4j
  47. @Component
  48. public class UploadToOssUtil {
  49. @Value("${oss.point:http://oss-cn-shenzhen-internal.aliyuncs.com}")
  50. private String point;
  51. @Value("${oss.key:LTAIUrvuHqj8pvry}")
  52. private String key;
  53. @Value("${oss.secrey:JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4}")
  54. private String secrey;
  55. @Value("${oss.bucket:4dkankan}")
  56. private String bucket;
  57. @Value("${oss.sdk:4dscene}")
  58. private String bucketSdk;
  59. @Value("${upload.type:oss}")
  60. private String type;
  61. @Value("${aws.s3key:AKIAWCV5QFZ3ZNELKYUY}")
  62. private String s3key;
  63. @Value("${aws.s3secrey:epS5ghyR4LJ7rxk/qJO9ZYh6m9Oz6g5haKDu4yws}")
  64. private String s3secrey;
  65. @Value("${aws.s3bucket:4dkankan}")
  66. private String s3bucket;
  67. @Value("${local.path:/home/4dkankan}")
  68. private String localPath;
  69. /**
  70. * oss文件上传命令
  71. * 第一个参数是oss路径,要包含bucket名称
  72. * 第二个参数是本地文件路径
  73. */
  74. private static final String UPLOAD_SH = "bash /opt/ossutil/upload.sh %s %s";
  75. public static final String FYUN_UPLOAD = "sudo bash /opt/ossutil/fyun-upload.sh %s %s /%s %s %s";
  76. //上传的数据是byte[],key是上传后的文件名
  77. public void upload(String bucket, byte[] data,String key1) throws IOException{
  78. log.info("开始上传文件 源路径:{},目标路径:{},type:{}" , new String(data, "UTF-8"),key1,type);
  79. StorageType storageType = StorageType.get(type);
  80. switch (storageType){
  81. case OSS:
  82. uploadOss(bucket, data,key1);
  83. break;
  84. case AWS:
  85. uploadAws(bucket, data,key1);
  86. break;
  87. case LOCAL:
  88. uploadLocal(data,key1);
  89. break;
  90. }
  91. }
  92. public void upload(String bucket, String filePath, String key1) {
  93. log.info("开始上传文件 源路径:{},目标路径:{},type:{}" , filePath,key1,type);
  94. StorageType storageType = StorageType.get(type);
  95. switch (storageType){
  96. case OSS:
  97. uploadOss(bucket, filePath,key1);
  98. break;
  99. case AWS:
  100. uploadAws(bucket, filePath,key1);
  101. break;
  102. case LOCAL:
  103. uploadLocal(filePath,key1);
  104. break;
  105. }
  106. }
  107. /**
  108. * 通过脚本上传
  109. * @param filePath
  110. * @param key
  111. */
  112. public void uploadBySh(String bucket, String filePath, String key) {
  113. String command = String.format(FYUN_UPLOAD, bucket, filePath, key, type, "file");
  114. try {
  115. log.info("开始上传文件, ossPath:{}, srcPath:{}", key, filePath);
  116. callshell(command);
  117. log.info("上传文件完毕, ossPath:{}, srcPath:{}", key, filePath);
  118. } catch(Exception e) {
  119. log.error("上传文件失败, ossPath:{}, srcPath:{}", key, filePath);
  120. log.error("上传文件失败", e);
  121. }
  122. }
  123. public static void callshell(String command){
  124. try {
  125. Long start = System.currentTimeMillis();
  126. Process process = Runtime.getRuntime().exec(command);
  127. StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
  128. errorGobbler.start();
  129. StreamGobbler outGobbler = new StreamGobbler(process.getInputStream(), "STDOUT");
  130. outGobbler.start();
  131. process.waitFor();
  132. log.info("脚本{}执行完毕,用时:{}ms",command,System.currentTimeMillis()-start);
  133. } catch (Exception e) {
  134. e.printStackTrace();
  135. }
  136. }
  137. public void uploadSdk(String bucket, String filePath, String key1) {
  138. log.info("开始上传文件 源路径:{},目标路径:{},type:{}" , filePath,key1,type);
  139. switch (type){
  140. case "oss":uploadSdkOss(bucket, filePath, key1); break;
  141. case "aws": uploadAws(bucket, filePath, key1); break;
  142. case "local":uploadLocal(filePath,key1); break;
  143. }
  144. }
  145. public void upload2(String bucket, String filePath, String key1) {
  146. log.info("开始上传文件 源路径:{},目标路径:{},type:{}" , filePath,key1,type);
  147. switch (type){
  148. case "oss":upload2Oss(bucket, filePath,key1); break;
  149. case "aws": uploadAws(bucket, filePath,key1); break;
  150. case "local":uploadLocal(filePath,key1); break;
  151. }
  152. }
  153. public void delete(String bucket, String key1) throws IOException{
  154. switch (type){
  155. case "oss":deleteOss(bucket, key1); break;
  156. case "aws": deleteS3Object(bucket, key1); break;
  157. case "local":FileUtil.del(key1); break;
  158. }
  159. }
  160. /**
  161. * 删除目录或者文件
  162. * @param prefix
  163. * @return
  164. */
  165. public int deleteFile(String bucket, String prefix){
  166. switch (type){
  167. case "oss":deleteOssFile(bucket, prefix); break;
  168. case "aws": deleteAwsFile(bucket, prefix); break;
  169. case "local":FileUtil.del(prefix); break;
  170. }
  171. return 1;
  172. }
  173. public void deleteOss(String bucket, String objectName){
  174. OSSClient ossClient = new OSSClient(point, key, secrey);
  175. try {
  176. ossClient.deleteObject(bucket, objectName);
  177. } catch (Exception e) {
  178. log.error("OSS删除文件失败,key=" + objectName);
  179. }finally {
  180. if(ossClient != null){
  181. ossClient.shutdown();
  182. }
  183. }
  184. }
  185. public void deleteOssFile(String bucket, String prefix){
  186. int maxKeys = 200;
  187. OSSClient ossClient = new OSSClient(point, key, secrey);
  188. try {
  189. String nextMarker = null;
  190. ObjectListing objectListing;
  191. do {
  192. objectListing = ossClient.listObjects(new ListObjectsRequest(bucket).withPrefix(prefix).withMarker(nextMarker).withMaxKeys(maxKeys));
  193. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  194. if (CollUtil.isEmpty(sums)) {
  195. return;
  196. }
  197. List<String> keys = new ArrayList<>();
  198. for (OSSObjectSummary sum : sums) {
  199. keys.add(sum.getKey());
  200. }
  201. DeleteObjectsRequest deleteObjectsRequest =
  202. new DeleteObjectsRequest(bucket).withKeys(keys).withEncodingType("url");
  203. DeleteObjectsResult deleteObjectsResult = ossClient
  204. .deleteObjects(deleteObjectsRequest);
  205. List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
  206. try {
  207. for (String deletedObject : deletedObjects) {
  208. String decode = URLDecoder.decode(deletedObject, "UTF-8");
  209. log.info("删除oss文件:{}", decode);
  210. }
  211. } catch (UnsupportedEncodingException e) {
  212. e.printStackTrace();
  213. }
  214. }while (objectListing.isTruncated());
  215. }catch (Exception e){
  216. e.printStackTrace();
  217. }finally {
  218. if(ossClient != null){
  219. ossClient.shutdown();
  220. }
  221. }
  222. }
  223. private void deleteAwsFile(String bucket, String prefix){
  224. int maxKeys = 200;
  225. String nextMaker = null;
  226. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  227. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  228. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  229. .withRegion(Regions.EU_WEST_2)
  230. .build();
  231. try {
  232. com.amazonaws.services.s3.model.ListObjectsRequest listObjectsRequest = new com.amazonaws.services.s3.model.ListObjectsRequest();
  233. listObjectsRequest.setBucketName(bucket);
  234. listObjectsRequest.setPrefix(prefix);
  235. listObjectsRequest.setMaxKeys(maxKeys);
  236. com.amazonaws.services.s3.model.ObjectListing objectListing;
  237. do{
  238. listObjectsRequest.setMarker(nextMaker);
  239. objectListing = s3.listObjects(listObjectsRequest);
  240. List<S3ObjectSummary> objectSummaries = objectListing.getObjectSummaries();
  241. List<KeyVersion> keys =objectSummaries.stream().map(summary->new KeyVersion(summary.getKey())).collect(Collectors.toList());
  242. com.amazonaws.services.s3.model.DeleteObjectsRequest multiObjectDeleteRequest =
  243. new com.amazonaws.services.s3.model.DeleteObjectsRequest(bucket)
  244. .withKeys(keys)
  245. .withQuiet(false);
  246. com.amazonaws.services.s3.model.DeleteObjectsResult delObjRes = s3.deleteObjects(multiObjectDeleteRequest);
  247. int successfulDeletes = delObjRes.getDeletedObjects().size();
  248. log.info("删除aws文件成功,删除文件数;{}", successfulDeletes);
  249. nextMaker = objectListing.getNextMarker();
  250. }while (objectListing.isTruncated());
  251. }catch (Exception e){
  252. log.error("删除was文件失败,path="+prefix, e);
  253. }finally {
  254. if(s3 != null){
  255. s3.shutdown();
  256. }
  257. }
  258. }
  259. public void uploadOss(String bucket, byte[] data,String objectName){
  260. OSSClient ossClient = new OSSClient(point, key, secrey);
  261. try {
  262. ossClient.putObject(bucket, objectName, new ByteArrayInputStream(data));
  263. } catch (Exception e) {
  264. log.error("oss上传文件失败", e);
  265. }finally {
  266. if(ossClient != null){
  267. ossClient.shutdown();
  268. }
  269. }
  270. }
  271. public void uploadAws(String bucket, byte[] data,String objectName){
  272. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  273. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  274. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  275. .withRegion(Regions.EU_WEST_2)
  276. .build();
  277. try {
  278. com.amazonaws.services.s3.model.ObjectMetadata metadata = new com.amazonaws.services.s3.model.ObjectMetadata();
  279. PutObjectRequest request = new PutObjectRequest(bucket, objectName, new ByteArrayInputStream(data), metadata);
  280. request.withCannedAcl(CannedAccessControlList.PublicRead);
  281. s3.putObject(request);
  282. }catch (Exception e){
  283. log.error("s3上传文件失败", e);
  284. }finally {
  285. if(s3 != null){
  286. s3.shutdown();
  287. }
  288. }
  289. }
  290. public void uploadLocal(byte[] data,String key1){
  291. InputStream in = new ByteArrayInputStream(data);
  292. File file = new File(key1);
  293. String path = key1.substring(0, key1.lastIndexOf("/"));
  294. if (!file.exists()) {
  295. new File(path).mkdir();
  296. }
  297. FileOutputStream fos = null;
  298. try {
  299. fos = new FileOutputStream(file);
  300. int len = 0;
  301. byte[] buf = new byte[1024];
  302. while ((len = in.read(buf)) != -1) {
  303. fos.write(buf, 0, len);
  304. }
  305. fos.flush();
  306. } catch (Exception e) {
  307. e.printStackTrace();
  308. } finally {
  309. if (null != fos) {
  310. try {
  311. fos.close();
  312. } catch (IOException e) {
  313. e.printStackTrace();
  314. }
  315. }
  316. }
  317. }
  318. public void uploadOss(String bucket, String filePath, String key1){
  319. OSSClient ossClient = new OSSClient(point, key, secrey);
  320. try {
  321. File file = new File(filePath);
  322. if (!file.exists()) {
  323. log.error("要上传的文件不存在:" + filePath);
  324. return;
  325. }
  326. ObjectMetadata metadata = new ObjectMetadata();
  327. if(filePath.contains(".jpg")){
  328. metadata.setContentType("image/jpeg");
  329. }
  330. ossClient.putObject(bucket, key1, new File(filePath), metadata);
  331. } catch (Exception e) {
  332. log.error(e.toString() + filePath);
  333. } finally {
  334. ossClient.shutdown();
  335. }
  336. }
  337. public void uploadAws(String bucket, String filePath, String key1){
  338. try{
  339. uploadS3File(bucket, filePath, key1);
  340. }catch (Exception e){
  341. e.printStackTrace();
  342. }
  343. }
  344. public void uploadLocal(String filePath, String key1){
  345. try {
  346. File srcFile = new File(filePath);
  347. File file = new File(localPath + key1);
  348. FileUtils.copyFile(srcFile,file);
  349. }catch (Exception e){
  350. e.printStackTrace();
  351. }
  352. }
  353. public void uploadSdkOss(String bucket, String filePath, String key1){
  354. OSSClient ossClient = new OSSClient(point, key, secrey);
  355. try {
  356. File file = new File(filePath);
  357. if (!file.exists()) {
  358. log.error("要上传的文件不存在:" + filePath);
  359. return;
  360. }
  361. ObjectMetadata metadata = new ObjectMetadata();
  362. if(filePath.contains(".jpg")){
  363. metadata.setContentType("image/jpeg");
  364. }
  365. ossClient.putObject(bucket, key1, new File(filePath), metadata);
  366. } catch (Exception e) {
  367. log.error(e.toString() + filePath);
  368. }
  369. }
  370. public void upload2Oss(String bucket, String filePath, String key1){
  371. OSSClient ossClient = new OSSClient(point, key, secrey);
  372. try {
  373. ObjectMetadata metadata = new ObjectMetadata();
  374. if(filePath.contains(".jpg")){
  375. metadata.setContentType("image/jpeg");
  376. }
  377. if(filePath.contains(".mp4")){
  378. metadata.setContentType("video/mp4");
  379. }
  380. if(filePath.contains(".mp3")){
  381. metadata.setContentType("audio/mp3");
  382. }
  383. ossClient.putObject(bucket, key1, new File(filePath), metadata);
  384. } catch (Exception e) {
  385. log.error(e.toString() + filePath);
  386. }
  387. }
  388. //上传的数据是文件夹,参数是文件夹路径,key是上传后的文件名
  389. public void uploadMulFiles(String bucket, Map<String, String> filepaths) {
  390. if (filepaths == null) {
  391. return;
  392. }
  393. Long start = System.currentTimeMillis();
  394. log.info("开始批量上传文件:");
  395. if (filepaths.size() > 50) {
  396. filepaths.entrySet().parallelStream().forEach(entry->{
  397. upload2(bucket, entry.getKey(), entry.getValue());
  398. });
  399. } else {
  400. filepaths.entrySet().parallelStream().forEach(entry->{
  401. upload(bucket, entry.getKey(), entry.getValue());
  402. });
  403. }
  404. log.info("批量上传文件结束,用时:{}" ,(System.currentTimeMillis() - start));
  405. }
  406. public Map<String, String> getUploadS3Url(List<String> urls){
  407. if(urls == null || urls.size() <= 0){
  408. return null;
  409. }
  410. BasicAWSCredentials awsCred = new BasicAWSCredentials(s3key, s3secrey);
  411. AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
  412. .withCredentials(new AWSStaticCredentialsProvider(awsCred))
  413. .withRegion(Regions.EU_WEST_2)
  414. .build();
  415. // Set the pre-signed URL to expire after one hour.
  416. java.util.Date expiration = new java.util.Date();
  417. long expTimeMillis = expiration.getTime();
  418. expTimeMillis += 1000 * 60 * 60 * 8;
  419. expiration.setTime(expTimeMillis);
  420. //生成预签名URL
  421. log.info("生成预签名URL");
  422. GeneratePresignedUrlRequest generatePresignedUrlRequest = null;
  423. URL url = null;
  424. Map<String, String> map = new HashMap();
  425. for(String path : urls){
  426. // if(path.contains(".jpg") || path.contains("png")){
  427. // generatePresignedUrlRequest = new GeneratePresignedUrlRequest(s3bucket, path)
  428. // .withMethod(HttpMethod.PUT)
  429. // .withExpiration(expiration)
  430. // .withContentType("image/jpeg");
  431. // }else {
  432. generatePresignedUrlRequest = new GeneratePresignedUrlRequest(s3bucket, path)
  433. .withMethod(HttpMethod.PUT)
  434. .withExpiration(expiration);
  435. // }
  436. url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
  437. map.put(path, url.toString());
  438. }
  439. return map;
  440. }
  441. public String upload5(String filePath, String key1) {
  442. OSSClient ossClient = new OSSClient(point, key, secrey);
  443. PutObjectResult result = null;
  444. try {
  445. File file = new File(filePath);
  446. if (!file.exists()) {
  447. log.error("要上传的文件不存在:" + filePath);
  448. }
  449. result = ossClient.putObject(bucket, key1, new File(filePath));
  450. } catch (Exception e) {
  451. log.error(e.toString() + filePath);
  452. }
  453. log.info(" getETag : " + result.getETag());
  454. log.info("1 : " + result.toString());
  455. log.info("2 : " + result.getRequestId());
  456. log.info("3 : " + result.getClientCRC());
  457. log.info("4 : " + result.getResponse());
  458. log.info("5 : " + result.getServerCRC());
  459. return result.getETag();
  460. }
  461. //海外亚马逊s3
  462. /**
  463. * s3上传文件流
  464. *
  465. * @param file 文件
  466. * @param updatePath 上传路径[ eg: xxx/xxx ]
  467. */
  468. public String updateS3LoadFile(String bucket, MultipartFile file, String updatePath) {
  469. if (isEmpty(file)) {
  470. return null;
  471. }
  472. /**
  473. * 创建s3对象
  474. */
  475. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  476. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  477. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  478. .withRegion(Regions.EU_WEST_2)
  479. .build();
  480. try {
  481. // 创建临时文件,程序运行结束,会自动删除
  482. File localFile = File.createTempFile("temp", null);
  483. // 把文件写入内存中
  484. file.transferTo(localFile);
  485. // 指定要上传到服务器上的路径
  486. String key = updatePath;
  487. // 设置文件并设置公读
  488. PutObjectRequest request = new PutObjectRequest(bucket, key, localFile);
  489. request.withCannedAcl(CannedAccessControlList.PublicRead);
  490. // 上传文件
  491. com.amazonaws.services.s3.model.PutObjectResult putObjectResult = s3.putObject(request);
  492. if (StringUtils.isNotEmpty(putObjectResult.getETag())) {
  493. System.out.println("success");
  494. return key;
  495. }
  496. return null;
  497. } catch (IOException e) {
  498. }
  499. return null;
  500. }
  501. /**
  502. * s3上传文件
  503. * @param filePath
  504. * @param key1
  505. * @throws IOException
  506. */
  507. private void uploadS3File(String bucket, String filePath, String key1) throws Exception {
  508. /**
  509. * 创建s3对象
  510. */
  511. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  512. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  513. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  514. .withRegion(Regions.EU_WEST_2)
  515. .build();
  516. try{
  517. File file = new File(filePath);
  518. if(!file.exists()){
  519. log.info("要上传s3的文件不存在");
  520. return;
  521. }
  522. // 设置文件并设置公读
  523. com.amazonaws.services.s3.model.ObjectMetadata metadata = new com.amazonaws.services.s3.model.ObjectMetadata();
  524. if(filePath.contains(".jpg")){
  525. metadata.setContentType("image/jpeg");
  526. }
  527. if(filePath.contains(".png")){
  528. metadata.setContentType("image/png");
  529. }
  530. PutObjectRequest request = new PutObjectRequest(bucket, key1, file);
  531. request.withCannedAcl(CannedAccessControlList.PublicRead);
  532. request.withMetadata(metadata);
  533. // 上传文件
  534. com.amazonaws.services.s3.model.PutObjectResult putObjectResult = s3.putObject(request);
  535. if (StringUtils.isNotEmpty(putObjectResult.getETag())) {
  536. log.info("s3上传文件成功:" + key1);
  537. }
  538. }catch (Exception e){
  539. throw e;
  540. }finally {
  541. s3.shutdown();
  542. }
  543. }
  544. /**
  545. * 删除单个文件
  546. *
  547. * @param objectName 文件路径[ eg: /head/xxxx.jpg ]
  548. * @return
  549. */
  550. public void deleteS3Object(String bucket, String objectName) {
  551. /**
  552. * 创建s3对象
  553. */
  554. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  555. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  556. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  557. .withRegion(Regions.EU_WEST_2)
  558. .build();
  559. if (objectName.startsWith("/")) {
  560. objectName = objectName.substring(1);
  561. }
  562. try {
  563. s3.deleteObject(bucket, objectName);
  564. } catch (Exception e) {
  565. log.error("s3删除文件失败,key="+objectName, e);
  566. }finally {
  567. if(s3 != null){
  568. s3.shutdown();
  569. }
  570. }
  571. }
  572. /**
  573. * 获取文件类型
  574. */
  575. public static String getContentType(String filePath){
  576. FileNameMap fileNameMap = URLConnection.getFileNameMap();
  577. String contentType = fileNameMap.getContentTypeFor(filePath);
  578. System.out.println(contentType);
  579. return contentType;
  580. }
  581. /**
  582. * 检查文件是否为空
  583. *
  584. * @param imageFile
  585. * @return
  586. */
  587. private static boolean isEmpty(MultipartFile imageFile) {
  588. if (imageFile == null || imageFile.getSize() <= 0) {
  589. return true;
  590. }
  591. return false;
  592. }
  593. private static MultipartFile getMulFileByPath(String picPath) {
  594. FileItem fileItem = createFileItem(picPath);
  595. MultipartFile mfile = new CommonsMultipartFile(fileItem);
  596. return mfile;
  597. }
  598. private static FileItem createFileItem(String filePath) {
  599. FileItemFactory factory = new DiskFileItemFactory(16, null);
  600. String textFieldName = "textField";
  601. int num = filePath.lastIndexOf(".");
  602. String extFile = filePath.substring(num);
  603. FileItem item = factory.createItem(textFieldName, "text/plain", true,
  604. "MyFileName" + extFile);
  605. File newfile = new File(filePath);
  606. int bytesRead = 0;
  607. byte[] buffer = new byte[8192];
  608. try
  609. {
  610. FileInputStream fis = new FileInputStream(newfile);
  611. OutputStream os = item.getOutputStream();
  612. while ((bytesRead = fis.read(buffer, 0, 8192))
  613. != -1)
  614. {
  615. os.write(buffer, 0, bytesRead);
  616. }
  617. os.close();
  618. fis.close();
  619. }
  620. catch (IOException e)
  621. {
  622. e.printStackTrace();
  623. }
  624. return item;
  625. }
  626. public List<String> listKeys(String bucket, String sourcePath){
  627. StorageType storageType = StorageType.get(type);
  628. switch (storageType){
  629. case OSS:
  630. return this.listKeysFromAli(bucket, sourcePath);
  631. case AWS:
  632. return this.listKeysFromAws(bucket, sourcePath);
  633. case LOCAL:
  634. return this.listKeysFromLocal(sourcePath);
  635. }
  636. return null;
  637. }
  638. /**
  639. * 获得文件列表-阿里云
  640. * @return
  641. */
  642. public List<String> listKeysFromAli(String bucket, String sourcePath) {
  643. List<String> keyList = new ArrayList<>();
  644. OSSClient ossClient = new OSSClient(point, key, secrey);
  645. try {
  646. boolean flag = true;
  647. String nextMaker = null;
  648. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket);
  649. //指定下一级文件
  650. listObjectsRequest.setPrefix(sourcePath);
  651. //设置分页的页容量
  652. listObjectsRequest.setMaxKeys(200);
  653. do
  654. {
  655. //获取下一页的起始点,它的下一项
  656. listObjectsRequest.setMarker(nextMaker);
  657. ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
  658. List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
  659. List<String> collect = objectSummaries.stream().map(summary -> {
  660. return summary.getKey();
  661. }).collect(Collectors.toList());
  662. if(CollUtil.isNotEmpty(collect)){
  663. keyList.addAll(collect);
  664. }
  665. nextMaker = objectListing.getNextMarker();
  666. //全部执行完后,为false
  667. flag = objectListing.isTruncated();
  668. } while (flag);
  669. }catch (Exception e){
  670. log.error("获取文件列表失败,path="+sourcePath, e);
  671. }finally {
  672. if(ossClient != null){
  673. ossClient.shutdown();
  674. }
  675. }
  676. ossClient.shutdown();
  677. return keyList;
  678. }
  679. /**
  680. * 获得文件列表-亚马逊
  681. * @return
  682. */
  683. public List<String> listKeysFromAws(String bucket, String sourcePath) {
  684. List<String> keyList = new ArrayList<>();
  685. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  686. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  687. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  688. .withRegion(Regions.EU_WEST_2)
  689. .build();
  690. try {
  691. boolean flag = true;
  692. String nextMaker = null;
  693. com.amazonaws.services.s3.model.ListObjectsRequest listObjectsRequest = new com.amazonaws.services.s3.model.ListObjectsRequest();
  694. listObjectsRequest.setBucketName(bucket);
  695. listObjectsRequest.setPrefix(sourcePath);
  696. listObjectsRequest.setMaxKeys(200);
  697. do{
  698. listObjectsRequest.setMarker(nextMaker);
  699. com.amazonaws.services.s3.model.ObjectListing objectListing = s3.listObjects(listObjectsRequest);
  700. List<S3ObjectSummary> objectSummaries = objectListing.getObjectSummaries();
  701. List<String> collect =objectSummaries.stream().map(summary->{
  702. return summary.getKey();
  703. }).collect(Collectors.toList());
  704. if(CollUtil.isNotEmpty(collect)){
  705. keyList.addAll(collect);
  706. }
  707. nextMaker = objectListing.getNextMarker();
  708. flag = objectListing.isTruncated();
  709. }while (flag);
  710. }catch (Exception e){
  711. log.error("获取文件列表失败,path="+sourcePath, e);
  712. }finally {
  713. if(s3 != null){
  714. s3.shutdown();
  715. }
  716. }
  717. return keyList;
  718. }
  719. /**
  720. * 获得文件列表-阿里云
  721. * @return
  722. */
  723. public List<String> listKeysFromLocal(String sourcePath) {
  724. List<String> keyList = new ArrayList<>();
  725. return keyList;
  726. }
  727. /**
  728. * <p>
  729. 拷贝目录
  730. * </p>
  731. * @author dengsixing
  732. * @date 2022/1/18
  733. * @param sourcePath
  734. * @param targetPath
  735. **/
  736. public void copyFiles(String sourceBucketName, String sourcePath, String targetBucketName, String targetPath) throws IOException {
  737. StorageType storageType = StorageType.get(type);
  738. switch (storageType){
  739. case OSS:
  740. this.copyFilesFromAli(sourceBucketName, sourcePath, targetBucketName, targetPath);
  741. break;
  742. case AWS:
  743. this.copyFilesFromAws(sourceBucketName, sourcePath, targetBucketName, targetPath);
  744. break;
  745. case LOCAL: this.copyFilesFromLocal(sourcePath, targetPath);
  746. }
  747. }
  748. /**
  749. * <p>
  750. 拷贝文件
  751. * </p>
  752. * @author dengsixing
  753. * @date 2022/1/18
  754. * @param sourceKey
  755. * @param targetKey
  756. **/
  757. public void copyObject(String sourceBucketName, String sourceKey, String targetBucketName, String targetKey) throws IOException {
  758. StorageType storageType = StorageType.get(type);
  759. switch (storageType){
  760. case OSS:
  761. this.copyObjectFromAli(sourceBucketName, sourceKey, targetBucketName, targetKey);
  762. break;
  763. case AWS:
  764. this.copyObjectFromAws(sourceBucketName, sourceKey, targetBucketName, targetKey);
  765. break;
  766. }
  767. }
  768. /**
  769. * <p>
  770. 拷贝-阿里云
  771. * </p>
  772. * @author dengsixing
  773. * @date 2022/1/18
  774. * @param sourcePath
  775. * @param targetPath
  776. **/
  777. public void copyObjectFromAli(String sourceBucketName, String sourcePath, String targetBucketName, String targetPath) throws IOException {
  778. // 创建OSSClient实例。
  779. OSSClient ossClient = new OSSClient(point, key, secrey);
  780. // 复制文件
  781. log.info("开始复制:" + sourcePath);
  782. ossClient.copyObject(sourceBucketName, sourcePath, targetBucketName, targetPath);
  783. log.info("复制成功:" + sourcePath);
  784. ossClient.shutdown();
  785. }
  786. /**
  787. * <p>
  788. 拷贝-阿里云
  789. * </p>
  790. * @author dengsixing
  791. * @date 2022/1/18
  792. * @param sourcePath
  793. * @param targetPath
  794. **/
  795. public void copyFilesFromAli(String sourceBucketName, String sourcePath, String targetBucketName, String targetPath) throws IOException {
  796. //获取源文件列表
  797. List<String> sourceKeyList = this.listKeysFromAli(sourceBucketName, sourcePath);
  798. if(CollUtil.isEmpty(sourceKeyList)){
  799. return;
  800. }
  801. // 创建OSSClient实例。
  802. OSSClient ossClient = new OSSClient(point, key, secrey);
  803. // 复制文件
  804. sourceKeyList.parallelStream().forEach(key -> {
  805. log.info("开始复制:" + key);
  806. ossClient.copyObject(sourceBucketName, key, targetBucketName, key.replace(sourcePath, targetPath));
  807. log.info("复制成功:" + key);
  808. });
  809. ossClient.shutdown();
  810. }
  811. /**
  812. * <p>
  813. 拷贝-亚马逊
  814. * </p>
  815. * @author dengsixing
  816. * @date 2022/1/18
  817. * @param sourcePath
  818. * @param targetPath
  819. **/
  820. public void copyFilesFromAws(String sourceBucketName, String sourcePath, String targetBucketName, String targetPath){
  821. try {
  822. List<String> sourceKeyList = this.listKeysFromAws(sourceBucketName, sourcePath);
  823. /**
  824. * 创建s3对象
  825. */
  826. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  827. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  828. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  829. .withRegion(Regions.EU_WEST_2)//s3 地区位置
  830. .build();
  831. // 复制文件
  832. sourceKeyList.parallelStream().forEach(key -> {
  833. log.info("开始复制:" + key);
  834. com.amazonaws.services.s3.model.CopyObjectRequest request =
  835. new com.amazonaws.services.s3.model.CopyObjectRequest(sourceBucketName, key, targetBucketName, key.replace(sourcePath, targetPath));
  836. request.withCannedAccessControlList(CannedAccessControlList.PublicRead);
  837. s3.copyObject(request);
  838. log.info("复制成功:" + key);
  839. });
  840. s3.shutdown();
  841. } catch (Exception ase) {
  842. log.error("amazonS拷贝异常 " + ase.getMessage(), ase);
  843. }
  844. }
  845. /**
  846. * <p>
  847. 拷贝-亚马逊
  848. * </p>
  849. * @author dengsixing
  850. * @date 2022/1/18
  851. * @param sourceKey
  852. * @param targetKey
  853. **/
  854. public void copyObjectFromAws(String sourceBucketName, String sourceKey, String targetBucketName, String targetKey){
  855. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  856. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  857. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  858. .withRegion(Regions.EU_WEST_2)//s3 地区位置
  859. .build();
  860. // 复制文件
  861. log.info("开始复制:" + sourceKey);
  862. s3.copyObject(sourceBucketName, sourceKey, targetBucketName, targetKey);
  863. log.info("复制成功:" + sourceKey);
  864. s3.shutdown();
  865. }
  866. /**
  867. * <p>
  868. 拷贝-本地
  869. * </p>
  870. * @author dengsixing
  871. * @date 2022/1/18
  872. * @param sourcePath
  873. * @param targetPath
  874. **/
  875. public void copyFilesFromLocal(String sourcePath, String targetPath) throws IOException {
  876. // TODO: 2022/1/21
  877. }
  878. /**
  879. * 获取文件内容
  880. * @param bucketName
  881. * @param objectName
  882. * @return
  883. */
  884. public String getObjectContent(String bucketName, String objectName){
  885. StorageType storageType = StorageType.get(type);
  886. switch (storageType){
  887. case OSS:
  888. return this.getObjectContentFromAli(bucketName, objectName);
  889. case AWS:
  890. return this.getObjectContentFromAws(bucketName, objectName);
  891. case LOCAL:
  892. return this.getObjectContentFromLocal(objectName);
  893. }
  894. return null;
  895. }
  896. /**
  897. * 获取文件内容-阿里云
  898. * @param bucketName
  899. * @param objectName
  900. * @return
  901. */
  902. public String getObjectContentFromAli(String bucketName, String objectName){
  903. //创建oss客户端
  904. OSSClient ossClient = new OSSClient(point, key, secrey);
  905. InputStream objectContent = null;
  906. StringBuilder contentJson = new StringBuilder();
  907. try {
  908. // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
  909. OSSObject ossObject = ossClient.getObject(bucketName, objectName);
  910. objectContent = ossObject.getObjectContent();
  911. try(BufferedReader reader = new BufferedReader(new InputStreamReader(objectContent))){
  912. while (true) {
  913. String line = reader.readLine();
  914. if (line == null) break;
  915. contentJson.append(line);
  916. }
  917. } catch (IOException e) {
  918. log.error("读取scene.json文件流失败", e);
  919. }
  920. }catch (Exception e){
  921. log.error("s3获取文件内容失败,key="+objectName, e);
  922. }finally {
  923. if(ossClient != null){
  924. ossClient.shutdown();
  925. }
  926. }
  927. return contentJson.toString();
  928. }
  929. /**
  930. * 获取文件内容-阿里云
  931. * @param objectName
  932. * @return
  933. */
  934. public boolean existOnAli(String bucket, String objectName){
  935. //创建oss客户端
  936. OSSClient ossClient = new OSSClient(point, key, secrey);
  937. // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
  938. try{
  939. boolean exist = ossClient.doesObjectExist(bucket, objectName);
  940. return exist;
  941. }catch (Exception e){
  942. log.error("s4判断是否存在key异常,key=" + objectName, e);
  943. }finally {
  944. if(ossClient != null){
  945. ossClient.shutdown();
  946. }
  947. }
  948. return false;
  949. }
  950. /**
  951. * 获取文件内容-亚马逊
  952. * @param bucketName
  953. * @param objectName
  954. * @return
  955. */
  956. public String getObjectContentFromAws(String bucketName, String objectName){
  957. try {
  958. /**
  959. * 创建s3对象
  960. */
  961. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  962. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  963. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  964. .withRegion(Regions.EU_WEST_2)
  965. .build();
  966. GetObjectRequest request = new GetObjectRequest(bucketName,objectName);
  967. S3Object object = s3.getObject(request);
  968. S3ObjectInputStream inputStream = object.getObjectContent();
  969. StringBuilder content = new StringBuilder();
  970. try(BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))){
  971. while (true) {
  972. String line = reader.readLine();
  973. if (line == null) break;
  974. content.append(line);
  975. }
  976. } catch (IOException e) {
  977. log.error("读取aws文件流失败", e);
  978. }
  979. return content.toString();
  980. } catch (Exception ase) {
  981. log.error("amazonS3下载文件异常 " + ase.getMessage(), ase);
  982. }
  983. return null;
  984. }
  985. /**
  986. * 获取文件内容-亚马逊
  987. * @param objectName
  988. * @return
  989. */
  990. public boolean existOnAws(String bucket, String objectName){
  991. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  992. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  993. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  994. .withRegion(Regions.EU_WEST_2)
  995. .build();
  996. try {
  997. boolean exist = s3.doesObjectExist(bucket, objectName);
  998. return exist;
  999. }catch (Exception e){
  1000. log.error("s4判断是否存在key异常,key=" + objectName, e);
  1001. }finally {
  1002. if(s3 != null){
  1003. s3.shutdown();
  1004. }
  1005. }
  1006. return false;
  1007. }
  1008. /**
  1009. * 判断key是否存在
  1010. * @param key
  1011. * @return
  1012. */
  1013. public boolean existKey(String bucket, String key){
  1014. StorageType storageType = StorageType.get(type);
  1015. switch (storageType){
  1016. case OSS:
  1017. return this.existOnAli(bucket, key);
  1018. case AWS:
  1019. return this.existOnAws(bucket, key);
  1020. default:
  1021. return false;
  1022. }
  1023. }
  1024. /**
  1025. * 获取文件内容-本地
  1026. * @param objectName
  1027. * @return
  1028. */
  1029. public String getObjectContentFromLocal(String objectName){
  1030. // TODO: 2022/1/21
  1031. return null;
  1032. }
  1033. /**
  1034. * oss下载文件到本地
  1035. * @param objectName
  1036. * @param localPath
  1037. */
  1038. public boolean download(String bucket, String objectName, String localPath){
  1039. StorageType storageType = StorageType.get(this.type);
  1040. switch (storageType){
  1041. case OSS:
  1042. return this.downFormAli(bucket, objectName, localPath);
  1043. case AWS:
  1044. return this.downFromS3(bucket, objectName, localPath);
  1045. }
  1046. return false;
  1047. }
  1048. /**
  1049. * 从阿里云oss下载文件到本地
  1050. * @param objectName 云端文件k地址
  1051. * @param localPath 本地文件地址
  1052. * @return
  1053. */
  1054. public boolean downFormAli(String bucket, String objectName, String localPath){
  1055. OSSClient ossClient = new OSSClient(point, key, secrey);
  1056. try {
  1057. com.aliyun.oss.model.GetObjectRequest request = new com.aliyun.oss.model.GetObjectRequest(bucket,objectName);
  1058. ossClient.getObject(request, new File(localPath));
  1059. return true;
  1060. }catch (Exception e){
  1061. log.error("阿里云oss文件下载失败,key=" + objectName, e);
  1062. }finally {
  1063. if(ossClient != null){
  1064. ossClient.shutdown();
  1065. }
  1066. }
  1067. return false;
  1068. }
  1069. /**
  1070. * 从s3下载文件到本地
  1071. * @param objectName 云端文件k地址
  1072. * @param localPath 本地文件地址
  1073. * @return
  1074. */
  1075. public boolean downFromS3(String bucket, String objectName, String localPath) {
  1076. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  1077. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  1078. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  1079. .withRegion(Regions.EU_WEST_2)
  1080. .build();
  1081. try {
  1082. GetObjectRequest request = new GetObjectRequest(bucket,objectName);
  1083. s3.getObject(request,new File(localPath));
  1084. return true;
  1085. } catch (Exception e) {
  1086. log.error("amazonS3下载文件失败,key=" + objectName, e);
  1087. }finally {
  1088. if(s3 != null){
  1089. s3.shutdown();
  1090. }
  1091. }
  1092. return false;
  1093. }
  1094. }