UploadToOssUtil.java 14 KB

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