UploadToOssUtil.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. package com.fdkankan.fyun.oss;
  2. import cn.hutool.core.collection.CollUtil;
  3. import com.aliyun.oss.OSSClient;
  4. import com.aliyun.oss.model.*;
  5. import com.amazonaws.HttpMethod;
  6. import com.amazonaws.auth.AWSStaticCredentialsProvider;
  7. import com.amazonaws.auth.BasicAWSCredentials;
  8. import com.amazonaws.regions.Regions;
  9. import com.amazonaws.services.s3.AmazonS3;
  10. import com.amazonaws.services.s3.AmazonS3ClientBuilder;
  11. import com.amazonaws.services.s3.model.CannedAccessControlList;
  12. import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
  13. import com.amazonaws.services.s3.model.GetObjectRequest;
  14. import com.amazonaws.services.s3.model.PutObjectRequest;
  15. import com.qiniu.common.Zone;
  16. import com.qiniu.storage.Configuration;
  17. import com.qiniu.storage.UploadManager;
  18. import lombok.extern.slf4j.Slf4j;
  19. import org.apache.commons.fileupload.FileItem;
  20. import org.apache.commons.fileupload.FileItemFactory;
  21. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  22. import org.apache.commons.lang3.StringUtils;
  23. import org.springframework.beans.factory.annotation.Value;
  24. import org.springframework.stereotype.Component;
  25. import org.springframework.web.multipart.MultipartFile;
  26. import org.springframework.web.multipart.commons.CommonsMultipartFile;
  27. import java.io.*;
  28. import java.net.FileNameMap;
  29. import java.net.URL;
  30. import java.net.URLConnection;
  31. import java.util.ArrayList;
  32. import java.util.HashMap;
  33. import java.util.List;
  34. import java.util.Map;
  35. @Slf4j
  36. @Component
  37. public class UploadToOssUtil {
  38. Zone zone = Zone.autoZone();
  39. Configuration config = new Configuration(zone);
  40. UploadManager uploadManager = new UploadManager(config);
  41. @Value("${oss.point:http://oss-cn-shenzhen-internal.aliyuncs.com}")
  42. private String point;
  43. @Value("${oss.key:LTAIUrvuHqj8pvry}")
  44. private String key;
  45. @Value("${oss.secrey:JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4}")
  46. private String secrey;
  47. @Value("${oss.bucket:4dkankan}")
  48. private String bucket;
  49. @Value("${oss.sdk:4dscene}")
  50. private String bucketSdk;
  51. @Value("${oss.type:oss}")
  52. private String type;
  53. @Value("${oss.s3key:AKIAWCV5QFZ3ZNELKYUY}")
  54. private String s3key;
  55. @Value("${oss.s3secrey:epS5ghyR4LJ7rxk/qJO9ZYh6m9Oz6g5haKDu4yws}")
  56. private String s3secrey;
  57. @Value("${oss.s3bucket:4dkankan}")
  58. private String s3bucket;
  59. public void delete(String key1) throws IOException{
  60. OSSClient ossClient = new OSSClient(point, key, secrey);
  61. try {
  62. // bucketMgr.delete(bucketname, key);
  63. // 2019-2-28 启动aliyun oss 空间
  64. ossClient.deleteObject(bucket, key1);
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. //上传的数据是byte[],key是上传后的文件名
  70. public void upload(byte[] data,String key1) throws IOException{
  71. OSSClient ossClient = new OSSClient(point, key, secrey);
  72. try
  73. {
  74. //bucketMgr.delete(bucketname, key);
  75. //Response res = uploadManager.put(data, key, getUpToken(key));
  76. // 2019-2-28 启动aliyun oss 空间
  77. ossClient.putObject(bucket, key1, new ByteArrayInputStream(data));
  78. //log.info(res.bodyString());
  79. } catch (Exception e) {
  80. log.error(e.toString()+key1);
  81. }
  82. }
  83. public void upload(String filePath, String key1) {
  84. log.info("开始上传文件 源路径:{},目标路径:{},point:{}" , filePath,key1,point);
  85. if("oss".equals(type)){
  86. OSSClient ossClient = new OSSClient(point, key, secrey);
  87. try {
  88. File file = new File(filePath);
  89. if (!file.exists()) {
  90. log.error("要上传的文件不存在:" + filePath);
  91. }
  92. ObjectMetadata metadata = new ObjectMetadata();
  93. if(filePath.contains(".jpg")){
  94. metadata.setContentType("image/jpeg");
  95. }
  96. ossClient.putObject(bucket, key1, new File(filePath), metadata);
  97. } catch (Exception e) {
  98. log.error(e.toString() + filePath);
  99. }
  100. }
  101. if("s3".equals(type)){
  102. try{
  103. uploadS3File(filePath, key1);
  104. }catch (Exception e){
  105. e.printStackTrace();
  106. }
  107. }
  108. }
  109. public void uploadSdk(String filePath, String key1) {
  110. if("oss".equals(type)){
  111. OSSClient ossClient = new OSSClient(point, key, secrey);
  112. try {
  113. File file = new File(filePath);
  114. if (!file.exists()) {
  115. log.error("要上传的文件不存在:" + filePath);
  116. }
  117. // 调用put方法上传
  118. // Response res = uploadManager.put(FilePath, key, getUpToken(key));
  119. // 打印返回的信息
  120. // log.info(res.bodyString());
  121. // 2019-2-28 启动aliyun oss 空间
  122. // ObjectMetadata meta = new ObjectMetadata();
  123. // meta.setCacheControl("no-cache");
  124. // ossClient.putObject(BUCKET_NAME, key, new File(filePath), meta);
  125. ObjectMetadata metadata = new ObjectMetadata();
  126. if(filePath.contains(".jpg")){
  127. metadata.setContentType("image/jpeg");
  128. }
  129. ossClient.putObject(bucketSdk, key1, new File(filePath), metadata);
  130. } catch (Exception e) {
  131. log.error(e.toString() + filePath);
  132. }
  133. }
  134. if("s3".equals(type)){
  135. try{
  136. uploadS3File(filePath, key1);
  137. }catch (Exception e){
  138. e.printStackTrace();
  139. }
  140. }
  141. }
  142. public void upload2(String filePath, String key1) {
  143. log.info("开始上传文件 源路径:{},目标路径:{},point:{}" , filePath,key1,point);
  144. if("oss".equals(type)){
  145. OSSClient ossClient = new OSSClient(point, key, secrey);
  146. try {
  147. // 调用put方法上传
  148. // Response res = uploadManager.put(FilePath, key, getUpToken(key));
  149. // 打印返回的信息
  150. // log.info(res.bodyString());
  151. // 2019-2-28 启动aliyun oss 空间
  152. ObjectMetadata metadata = new ObjectMetadata();
  153. if(filePath.contains(".jpg")){
  154. metadata.setContentType("image/jpeg");
  155. }
  156. if(filePath.contains(".mp4")){
  157. metadata.setContentType("video/mp4");
  158. }
  159. if(filePath.contains(".mp3")){
  160. metadata.setContentType("audio/mp3");
  161. }
  162. ossClient.putObject(bucket, key1, new File(filePath), metadata);
  163. } catch (Exception e) {
  164. log.error(e.toString() + filePath);
  165. }
  166. }
  167. if("s3".equals(type)){
  168. try{
  169. uploadS3File(filePath, key1);
  170. }catch (Exception e){
  171. e.printStackTrace();
  172. }
  173. }
  174. }
  175. //上传的数据是文件夹,参数是文件夹路径,key是上传后的文件名
  176. public void uploadMulFiles(Map<String, String> filepaths) {
  177. if (filepaths == null) {
  178. return;
  179. }
  180. Long start = System.currentTimeMillis();
  181. log.info("开始批量上传文件:");
  182. if (filepaths.size() > 50) {
  183. filepaths.entrySet().parallelStream().forEach(entry->{
  184. upload2(entry.getKey(), entry.getValue());
  185. });
  186. } else {
  187. filepaths.entrySet().parallelStream().forEach(entry->{
  188. upload(entry.getKey(), entry.getValue());
  189. });
  190. }
  191. log.info("批量上传文件结束,用时:{}" ,(System.currentTimeMillis() - start));
  192. }
  193. public int deleteFile(String prefix){
  194. if("oss".equals(type)){
  195. OSSClient ossClient = new OSSClient(point, key, secrey);
  196. ObjectListing objectListing = ossClient.listObjects(bucket, prefix);
  197. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  198. try {
  199. for (OSSObjectSummary s : sums) {
  200. delete(s.getKey());
  201. }
  202. } catch (IOException e) {
  203. e.printStackTrace();
  204. }
  205. }
  206. if("s3".equals(type)){
  207. deleteS3Object(prefix);
  208. }
  209. return 1;
  210. }
  211. public Map<String, String> getUploadS3Url(List<String> urls){
  212. if(urls == null || urls.size() <= 0){
  213. return null;
  214. }
  215. BasicAWSCredentials awsCred = new BasicAWSCredentials(s3key, s3secrey);
  216. AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
  217. .withCredentials(new AWSStaticCredentialsProvider(awsCred))
  218. .withRegion(Regions.EU_WEST_2)
  219. .build();
  220. // Set the pre-signed URL to expire after one hour.
  221. java.util.Date expiration = new java.util.Date();
  222. long expTimeMillis = expiration.getTime();
  223. expTimeMillis += 1000 * 60 * 60 * 8;
  224. expiration.setTime(expTimeMillis);
  225. //生成预签名URL
  226. log.info("生成预签名URL");
  227. GeneratePresignedUrlRequest generatePresignedUrlRequest = null;
  228. URL url = null;
  229. Map<String, String> map = new HashMap();
  230. for(String path : urls){
  231. // if(path.contains(".jpg") || path.contains("png")){
  232. // generatePresignedUrlRequest = new GeneratePresignedUrlRequest(s3bucket, path)
  233. // .withMethod(HttpMethod.PUT)
  234. // .withExpiration(expiration)
  235. // .withContentType("image/jpeg");
  236. // }else {
  237. generatePresignedUrlRequest = new GeneratePresignedUrlRequest(s3bucket, path)
  238. .withMethod(HttpMethod.PUT)
  239. .withExpiration(expiration);
  240. // }
  241. url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
  242. map.put(path, url.toString());
  243. }
  244. return map;
  245. }
  246. public String upload5(String filePath, String key1) {
  247. OSSClient ossClient = new OSSClient(point, key, secrey);
  248. PutObjectResult result = null;
  249. try {
  250. File file = new File(filePath);
  251. if (!file.exists()) {
  252. log.error("要上传的文件不存在:" + filePath);
  253. }
  254. result = ossClient.putObject(bucket, key1, new File(filePath));
  255. } catch (Exception e) {
  256. log.error(e.toString() + filePath);
  257. }
  258. log.info(" getETag : " + result.getETag());
  259. log.info("1 : " + result.toString());
  260. log.info("2 : " + result.getRequestId());
  261. log.info("3 : " + result.getClientCRC());
  262. log.info("4 : " + result.getResponse());
  263. log.info("5 : " + result.getServerCRC());
  264. return result.getETag();
  265. }
  266. //海外亚马逊s3
  267. /**
  268. * s3上传文件流
  269. *
  270. * @param file 文件
  271. * @param updatePath 上传路径[ eg: xxx/xxx ]
  272. */
  273. public String updateS3LoadFile(MultipartFile file, String updatePath) {
  274. if (isEmpty(file)) {
  275. return null;
  276. }
  277. /**
  278. * 创建s3对象
  279. */
  280. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  281. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  282. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  283. .withRegion(Regions.EU_WEST_2)
  284. .build();
  285. try {
  286. // 创建临时文件,程序运行结束,会自动删除
  287. File localFile = File.createTempFile("temp", null);
  288. // 把文件写入内存中
  289. file.transferTo(localFile);
  290. // 指定要上传到服务器上的路径
  291. String key = updatePath;
  292. // 设置文件并设置公读
  293. PutObjectRequest request = new PutObjectRequest(s3bucket, key, localFile);
  294. request.withCannedAcl(CannedAccessControlList.PublicRead);
  295. // 上传文件
  296. com.amazonaws.services.s3.model.PutObjectResult putObjectResult = s3.putObject(request);
  297. if (StringUtils.isNotEmpty(putObjectResult.getETag())) {
  298. System.out.println("success");
  299. return key;
  300. }
  301. return null;
  302. } catch (IOException e) {
  303. }
  304. return null;
  305. }
  306. /**
  307. * s3上传文件
  308. * @param filePath
  309. * @param key1
  310. * @throws IOException
  311. */
  312. private void uploadS3File(String filePath, String key1) throws IOException {
  313. File file = new File(filePath);
  314. if(!file.exists()){
  315. log.info("要上传s3的文件不存在");
  316. return;
  317. }
  318. /**
  319. * 创建s3对象
  320. */
  321. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  322. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  323. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  324. .withRegion(Regions.EU_WEST_2)
  325. .build();
  326. // 设置文件并设置公读
  327. com.amazonaws.services.s3.model.ObjectMetadata metadata = new com.amazonaws.services.s3.model.ObjectMetadata();
  328. if(filePath.contains(".jpg")){
  329. metadata.setContentType("image/jpeg");
  330. }
  331. if(filePath.contains(".png")){
  332. metadata.setContentType("image/png");
  333. }
  334. PutObjectRequest request = new PutObjectRequest(s3bucket, key1, file);
  335. request.withCannedAcl(CannedAccessControlList.PublicRead);
  336. request.withMetadata(metadata);
  337. // 上传文件
  338. com.amazonaws.services.s3.model.PutObjectResult putObjectResult = s3.putObject(request);
  339. if (StringUtils.isNotEmpty(putObjectResult.getETag())) {
  340. log.info("s3上传文件成功:" + key1);
  341. }
  342. }
  343. /**
  344. * 删除单个文件
  345. *
  346. * @param filePath 文件路径[ eg: /head/xxxx.jpg ]
  347. * @return
  348. */
  349. public void deleteS3Object(String filePath) {
  350. /**
  351. * 创建s3对象
  352. */
  353. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  354. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  355. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  356. .withRegion(Regions.EU_WEST_2)
  357. .build();
  358. if (filePath.startsWith("/")) {
  359. filePath = filePath.substring(1);
  360. }
  361. try {
  362. s3.deleteObject(s3bucket, filePath);
  363. } catch (Exception e) {
  364. }
  365. }
  366. /**
  367. * 获取文件类型
  368. */
  369. public static String getContentType(String filePath){
  370. FileNameMap fileNameMap = URLConnection.getFileNameMap();
  371. String contentType = fileNameMap.getContentTypeFor(filePath);
  372. System.out.println(contentType);
  373. return contentType;
  374. }
  375. /**
  376. * 检查文件是否为空
  377. *
  378. * @param imageFile
  379. * @return
  380. */
  381. private static boolean isEmpty(MultipartFile imageFile) {
  382. if (imageFile == null || imageFile.getSize() <= 0) {
  383. return true;
  384. }
  385. return false;
  386. }
  387. private static MultipartFile getMulFileByPath(String picPath) {
  388. FileItem fileItem = createFileItem(picPath);
  389. MultipartFile mfile = new CommonsMultipartFile(fileItem);
  390. return mfile;
  391. }
  392. private static FileItem createFileItem(String filePath)
  393. {
  394. FileItemFactory factory = new DiskFileItemFactory(16, null);
  395. String textFieldName = "textField";
  396. int num = filePath.lastIndexOf(".");
  397. String extFile = filePath.substring(num);
  398. FileItem item = factory.createItem(textFieldName, "text/plain", true,
  399. "MyFileName" + extFile);
  400. File newfile = new File(filePath);
  401. int bytesRead = 0;
  402. byte[] buffer = new byte[8192];
  403. try
  404. {
  405. FileInputStream fis = new FileInputStream(newfile);
  406. OutputStream os = item.getOutputStream();
  407. while ((bytesRead = fis.read(buffer, 0, 8192))
  408. != -1)
  409. {
  410. os.write(buffer, 0, bytesRead);
  411. }
  412. os.close();
  413. fis.close();
  414. }
  415. catch (IOException e)
  416. {
  417. e.printStackTrace();
  418. }
  419. return item;
  420. }
  421. /**
  422. * 下载文件
  423. * @param bucketName 桶名
  424. * @param remoteFileName 文件名
  425. * @param path 下载路径
  426. */
  427. public boolean downFromS3(String bucketName, String remoteFileName, String path) {
  428. try {
  429. /**
  430. * 创建s3对象
  431. */
  432. BasicAWSCredentials awsCreds = new BasicAWSCredentials(s3key, s3secrey);
  433. AmazonS3 s3 = AmazonS3ClientBuilder.standard()
  434. .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
  435. .withRegion(Regions.EU_WEST_2)
  436. .build();
  437. GetObjectRequest request = new GetObjectRequest(bucketName,remoteFileName);
  438. s3.getObject(request,new File(path));
  439. return true;
  440. } catch (Exception ase) {
  441. log.error("amazonS3下载文件异常 " + ase.getMessage(), ase);
  442. }
  443. return false;
  444. }
  445. /**
  446. * 获得文件列表
  447. * @return
  448. */
  449. public List<String> listKeys(String sourcePath) {
  450. OSSClient ossClient = new OSSClient(point, key, secrey);
  451. List<String> keyList = new ArrayList<>();
  452. boolean flag = true;
  453. String maker = null;
  454. do
  455. {
  456. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(this.bucket);
  457. listObjectsRequest.setPrefix(sourcePath); //指定下一级文件
  458. listObjectsRequest.setMarker(maker); //获取下一页的起始点,它的下一项
  459. listObjectsRequest.setMaxKeys(200);//设置分页的页容量
  460. // listObjectsRequest.setDelimiter("/");//跳出递归循环,只去指定目录下的文件。使用它时 Prefix文件路径要以“/”结尾
  461. ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
  462. List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
  463. for (OSSObjectSummary objectSummary : objectSummaries) {
  464. keyList.add(objectSummary.getKey());
  465. }
  466. maker = objectListing.getNextMarker();
  467. flag = objectListing.isTruncated();//全部执行完后,为false
  468. } while (flag);
  469. return keyList;
  470. }
  471. /**
  472. * <p>
  473. 拷贝
  474. * </p>
  475. * @author dengsixing
  476. * @date 2022/1/18
  477. * @param keyList
  478. * @param sourcePath
  479. * @param targetPath
  480. **/
  481. public void copyFiles(String sourcePath, String targetPath) throws IOException {
  482. //获取源文件列表
  483. List<String> sourceKeyList = this.listKeys(sourcePath);
  484. if(CollUtil.isEmpty(sourceKeyList)){
  485. return;
  486. }
  487. // 创建OSSClient实例。
  488. OSSClient ossClient = new OSSClient(point, key, secrey);
  489. // 复制文件
  490. sourceKeyList.parallelStream().forEach(key -> {
  491. log.info("开始复制:" + key);
  492. ossClient.copyObject(this.bucket, key, this.bucket, key.replace(sourcePath, targetPath));
  493. log.info("复制成功:" + key);
  494. });
  495. ossClient.shutdown();
  496. }
  497. }