AliyunOSS.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package cn.com.ty.lift.common.utils;
  2. import cn.hutool.core.collection.IterUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import com.aliyun.oss.OSS;
  5. import com.aliyun.oss.OSSClientBuilder;
  6. import com.aliyun.oss.model.*;
  7. import lombok.extern.slf4j.Slf4j;
  8. import java.io.*;
  9. import java.util.HashMap;
  10. import java.util.List;
  11. import java.util.Map;
  12. /**
  13. * <p>
  14. * aliyun OSS工具类
  15. * </p>
  16. * @author wcz
  17. * @since 2019/11/29
  18. */
  19. @Slf4j
  20. public class AliyunOSS {
  21. // Endpoint以杭州为例,其它Region请按实际情况填写。
  22. private String endpoint = "http://oss-cn-beijing.aliyuncs.com";
  23. // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
  24. private String accessKeyId = "LTAI4FkSqFZa6LH9HqAsVott";
  25. private String accessKeySecret = "w7GXuh5tf1hduQuZ2AzT3a4q14BI1i";
  26. //存储空间名
  27. private String bucketName = "temp15827479607";
  28. //OSSClient实例
  29. private OSS ossClient;
  30. /**
  31. * 无参构造,初始化oss
  32. */
  33. private AliyunOSS() {
  34. hint("Default");
  35. init();
  36. }
  37. /**
  38. * 全参构造方法
  39. *
  40. * @param endpoint
  41. * @param accessKeyId
  42. * @param accessKeySecret
  43. * @param bucketName
  44. */
  45. private AliyunOSS(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
  46. this.endpoint = endpoint;
  47. this.accessKeyId = accessKeyId;
  48. this.accessKeySecret = accessKeySecret;
  49. this.bucketName = bucketName;
  50. hint("Custom");
  51. init();
  52. }
  53. private void hint(String type){
  54. log.info("Hint: Using the {} Configuration To Create Aliyun OSS Client.",type);
  55. }
  56. /**
  57. * 初始化,创建OSSClient实例
  58. */
  59. private void init() {
  60. if (null == ossClient) {
  61. ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
  62. }
  63. }
  64. /**
  65. * 关闭OSSClient。
  66. */
  67. private void destroy() {
  68. if (null != ossClient) {
  69. ossClient.shutdown();
  70. }
  71. }
  72. /**
  73. * 设置bucketName
  74. *
  75. * @param bucketName
  76. */
  77. public void setBucketName(String bucketName) {
  78. this.bucketName = bucketName;
  79. }
  80. /**
  81. * static 无参构造方法
  82. *
  83. * @return
  84. */
  85. public static AliyunOSS me() {
  86. return new AliyunOSS();
  87. }
  88. /**
  89. * static 全参构造方法
  90. *
  91. * @param endpoint
  92. * @param accessKeyId
  93. * @param accessKeySecret
  94. * @param bucketName
  95. * @return
  96. */
  97. public static AliyunOSS me(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
  98. return new AliyunOSS(endpoint, accessKeyId, accessKeySecret, bucketName);
  99. }
  100. /**
  101. * @param
  102. * @return
  103. * @description 创建存储空间
  104. * 存储空间是OSS全局命名空间,相当于数据的容器,可以存储若干文件。 以下代码用于新建一个存储空间
  105. * @date 2019/11/29 10:30
  106. */
  107. public boolean createBucket(String bucketName) {
  108. if (StrUtil.isEmpty(bucketName)) {
  109. return false;
  110. }
  111. try {
  112. ossClient.createBucket(bucketName);
  113. return true;
  114. } catch (Exception e) {
  115. log.error("创建存储空间异常: {}", e);
  116. return false;
  117. } finally {
  118. destroy();
  119. }
  120. }
  121. /**
  122. * @param objectName 上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
  123. * @return
  124. * @description 上传文件,上传文件至OSS
  125. * @date 2019/11/29 10:31
  126. */
  127. public String putObject(String bucketName, String objectName, byte[] content) {
  128. try {
  129. // 上传内容到指定的存储空间(bucketName)并保存为指定的文件名称(objectName)。
  130. ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
  131. String url = getObjectUrl(bucketName, objectName);
  132. return url;
  133. } catch (Exception e) {
  134. log.error("上传文件异常: {}", e);
  135. return null;
  136. } finally {
  137. destroy();
  138. }
  139. }
  140. /**
  141. * 批量上传文件到oss,返回 key:objectName ,value:url
  142. *
  143. * @param bucketName
  144. * @param ossEntities
  145. * @return
  146. */
  147. public Map<String, String> putObjects(String bucketName, List<OssEntity> ossEntities) {
  148. try {
  149. if (IterUtil.isEmpty(ossEntities)) {
  150. return null;
  151. }
  152. Map<String, String> urls = new HashMap<>();
  153. ossEntities.forEach(entity -> {
  154. // 上传内容到指定的存储空间(bucketName)并保存为指定的文件名称(objectName)。
  155. String objectName = entity.getObjectName();
  156. ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(entity.getContent()));
  157. String url = getObjectUrl(bucketName, objectName);
  158. log.info("objectName: {}, url: {}", objectName, url);
  159. urls.put(objectName, url);
  160. });
  161. return urls;
  162. } catch (Exception e) {
  163. log.error("上传文件异常: {}", e);
  164. return null;
  165. } finally {
  166. destroy();
  167. }
  168. }
  169. public String putObject(String objectName, byte[] content) {
  170. if (StrUtil.isEmpty(objectName)) {
  171. return null;
  172. }
  173. return putObject(bucketName, objectName, content);
  174. }
  175. /**
  176. * @param
  177. * @return
  178. * @description 下载文件,获取文件的文本内容
  179. * @date 2019/11/29 10:32
  180. */
  181. public boolean getObject(String bucketName, String objectName) throws Exception {
  182. try {
  183. // 调用ossClient.getObject返回一个OSSObject实例,该实例包含文件内容及文件元信息。
  184. OSSObject ossObject = ossClient.getObject(bucketName, objectName);
  185. // 调用ossObject.getObjectContent获取文件输入流,可读取此输入流获取其内容。
  186. InputStream content = ossObject.getObjectContent();
  187. if (content != null) {
  188. BufferedReader reader = new BufferedReader(new InputStreamReader(content));
  189. while (true) {
  190. String line = reader.readLine();
  191. if (line == null) break;
  192. System.out.println("\n" + line);
  193. }
  194. // 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
  195. content.close();
  196. }
  197. return true;
  198. }catch (Exception e){
  199. log.error("获取文件异常:{}",e);
  200. return false;
  201. }finally {
  202. destroy();
  203. }
  204. }
  205. /**
  206. * @param
  207. * @return
  208. * @description 列举文件:列举指定存储空间下的文件。默认列举100个文件
  209. * @date 2019/11/29 10:38
  210. */
  211. public void listObjects(String bucketName) {
  212. // ossClient.listObjects返回ObjectListing实例,包含此次listObject请求的返回结果。
  213. ObjectListing objectListing = ossClient.listObjects(bucketName);
  214. // objectListing.getObjectSummaries获取所有文件的描述信息。
  215. for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
  216. System.out.println(" - " + objectSummary.getKey() + " " + "(size = " + objectSummary.getSize() + ")");
  217. }
  218. // 关闭OSSClient。
  219. destroy();
  220. }
  221. /**
  222. * @param
  223. * @return
  224. * @description 删除文件
  225. * @date 2019/11/29 10:44
  226. */
  227. public boolean deleteObject(String bucketName, String objectName) {
  228. // <yourObjectName>表示删除OSS文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
  229. try {
  230. // 删除文件。
  231. ossClient.deleteObject(bucketName, objectName);
  232. return true;
  233. } catch (Exception e) {
  234. log.error("删除文件异常: {}", e);
  235. return false;
  236. } finally {
  237. destroy();
  238. }
  239. }
  240. public boolean deleteObject(String objectName) {
  241. if (StrUtil.isEmpty(objectName)) {
  242. return false;
  243. }
  244. return deleteObject(bucketName, objectName);
  245. }
  246. public boolean putFile(String bucketName, String objectName, File file) {
  247. try {
  248. // 创建PutObjectRequest对象。
  249. PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file);
  250. // 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
  251. // ObjectMetadata metadata = new ObjectMetadata();
  252. // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
  253. // metadata.setObjectAcl(CannedAccessControlList.Private);
  254. // putObjectRequest.setMetadata(metadata);
  255. // 上传文件。
  256. ossClient.putObject(putObjectRequest);
  257. return true;
  258. } catch (Exception e) {
  259. log.error("上传文件异常: {}", e);
  260. return false;
  261. } finally {
  262. destroy();
  263. }
  264. }
  265. public boolean putFile(String objectName, File file) {
  266. if (StrUtil.isEmpty(objectName)) {
  267. return false;
  268. }
  269. return putFile(bucketName, objectName, file);
  270. }
  271. public File getFile(String bucketName, String objectName, File file) {
  272. try {
  273. // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
  274. ossClient.getObject(new GetObjectRequest(bucketName, objectName), file);
  275. return file;
  276. } catch (Exception e) {
  277. log.error("获取文件异常: {}", e);
  278. return null;
  279. } finally {
  280. destroy();
  281. }
  282. }
  283. public String getObjectUrl(String bucketName, String objectName) {
  284. if(StrUtil.hasEmpty(endpoint,objectName)){
  285. return null;
  286. }
  287. return endpoint.replace("//","//" + bucketName + ".") + "/" + objectName;
  288. }
  289. }