• Java 阿里云存储OSS,上传文件,删除文件


    1. package com.ruoyi.common.utils.aliyunoss;
    2. import com.alibaba.fastjson2.JSONObject;
    3. import com.aliyun.oss.ClientException;
    4. import com.aliyun.oss.OSS;
    5. import com.aliyun.oss.OSSClientBuilder;
    6. import com.aliyun.oss.OSSException;
    7. import com.aliyun.oss.model.CannedAccessControlList;
    8. import com.aliyun.oss.model.CreateBucketRequest;
    9. import com.aliyun.oss.model.PutObjectResult;
    10. import com.aliyun.oss.model.StorageClass;
    11. import com.ruoyi.common.config.RuoYiConfig;
    12. import com.ruoyi.common.exception.ServiceException;
    13. import com.ruoyi.common.utils.StringUtils;
    14. import com.ruoyi.common.utils.uuid.UUIDUtil;
    15. import org.springframework.web.multipart.MultipartFile;
    16. import java.io.FileInputStream;
    17. import java.io.InputStream;
    18. import java.util.HashMap;
    19. import java.util.Map;
    20. import java.util.UUID;
    21. public class OssUtil {
    22. public static void main(String[] angs){
    23. JSONObject map = new JSONObject();
    24. map.put("domain","oss-cn-zhangjiakou.aliyuncs.com");//不同区域上传域名是不同的
    25. map.put("bucketName","ceshi");//桶名称
    26. map.put("accessKeyId","123");
    27. map.put("accessKeySecret","123");
    28. map.put("filePath","C:\\Users\\86186\\Desktop\\sql\\新建文件夹\\测试.zip");//本地文件所在路径
    29.         
    30. map.put("bindDomain","http://域名/");
    31.         //上传文件
    32. fileLocalUpload(map);
    33.         
    34.         //删除时OSS文件url
    35.         map.put("imgUrl","http://域名/sdfg/dfg/dfg/99aa2fc3430f.png");
    36. fileDelete(map);
    37. }
    38. static Map getFilePath(String type){
    39. Map map = new HashMap<>();
    40. map.put("mp4","pdd_video");
    41. map.put("avi","pdd_video");
    42. map.put("wmv","pdd_video");
    43. map.put("mpg","pdd_video");
    44. map.put("mpeg","pdd_video");
    45. map.put("mov","pdd_video");
    46. map.put("rm","pdd_video");
    47. map.put("ram","pdd_video");
    48. map.put("swf","pdd_video");
    49. map.put("flv","pdd_video");
    50. map.put("ram","pdd_video");
    51. return map;
    52. }
    53. //上传文件
    54. public static String fileUpload(JSONObject json) {
    55. // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
    56. String http = "https://";
    57. String endpoint = json.getString("domain");//"oss-cn-beijing.aliyuncs.com";
    58. // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    59. String accessKeyId = json.getString("accessKeyId");//"LT";
    60. String accessKeySecret = json.getString("accessKeySecret");//"ui2oVSG";
    61. // 填写Bucket名称,例如examplebucket。
    62. String bucketName = json.getString("bucketName");//"";
    63. String bindDomain = json.getString("bindDomain");//绑定的域名
    64. // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
    65. // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
    66. MultipartFile file = (MultipartFile)json.get("file");
    67. //获取原文件名
    68. String fileName = file.getOriginalFilename();
    69. //获取文件后缀
    70. String suffixName = fileName.substring(fileName.lastIndexOf("."));
    71. String imgPath = json.getString("imgPath");
    72. String objectName = imgPath + UUIDUtil.get16UUID()+suffixName;
    73. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
    74. if(json.get("fileName") != null && StringUtils.isNotBlank(json.getString("fileName"))){
    75. objectName = imgPath + json.getString("fileName") + suffixName;
    76. }
    77. //String filePath = ;//"C:\\Users\\Administrator\\Desktop\\a02604f5cd493125abdf2cfcae98d2c1.mp4.f30.mp4";
    78. // 创建OSSClient实例。
    79. OSS ossClient = new OSSClientBuilder().build(http+endpoint, accessKeyId, accessKeySecret);
    80. PutObjectResult objectResult ;
    81. try {
    82. InputStream inputStream = file.getInputStream();;//new FileInputStream(filePath);
    83. // 创建PutObject请求。
    84. objectResult = ossClient.putObject(bucketName, objectName, inputStream);
    85. } catch (Exception e) {
    86. System.out.println("Error Message:" + e.getMessage());
    87. throw new ServiceException("文件上传失败:"+e.getMessage());
    88. } finally {
    89. if (ossClient != null) {
    90. ossClient.shutdown();
    91. }
    92. }
    93. String fileUrl = bindDomain+objectName;
    94. System.out.println(">>>>>>>>>>>>>>>>> 上传文件后的url:"+fileUrl);
    95. return fileUrl;
    96. }
    97. /**
    98. * 删除指定文件
    99. * @param json
    100. * @return
    101. */
    102. public static void fileDelete(JSONObject json) {
    103. // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
    104. String http = "https://";
    105. String endpoint = json.getString("domain");//"oss-cn-beijing.aliyuncs.com";
    106. // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    107. String accessKeyId = json.getString("accessKeyId");//"LTAnyDZ";
    108. String accessKeySecret = json.getString("accessKeySecret");//"VSG";
    109. // 填写Bucket名称,例如examplebucket。
    110. String bucketName = json.getString("bucketName");//"ndl";
    111. //绑定的域名
    112. String bindDomain = json.getString("bindDomain");
    113. // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
    114. String objectName = json.getString("imgUrl");
    115. //String yuming = http+bucketName+"."+ endpoint+"/";
    116. objectName = objectName.replace(bindDomain,"");
    117. // 创建OSSClient实例。
    118. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    119. try {
    120. // 删除文件或目录。如果要删除目录,目录必须为空。
    121. ossClient.deleteObject(bucketName, objectName);
    122. } catch (OSSException oe) {
    123. System.out.println("Caught an OSSException, which means your request made it to OSS, "
    124. + "but was rejected with an error response for some reason.");
    125. System.out.println("Error Message:" + oe.getErrorMessage());
    126. System.out.println("Error Code:" + oe.getErrorCode());
    127. System.out.println("Request ID:" + oe.getRequestId());
    128. System.out.println("Host ID:" + oe.getHostId());
    129. throw new ServiceException("文件删除失败:"+oe.getErrorMessage());
    130. } catch (ClientException ce) {
    131. System.out.println("Caught an ClientException, which means the client encountered "
    132. + "a serious internal problem while trying to communicate with OSS, "
    133. + "such as not being able to access the network.");
    134. System.out.println("Error Message:" + ce.getMessage());
    135. throw new ServiceException("文件删除失败:"+ce.getMessage());
    136. } finally {
    137. if (ossClient != null) {
    138. ossClient.shutdown();
    139. }
    140. }
    141. System.out.println(">>>>>>>>>>>>>>>删除文件:" + objectName+" 成功!");
    142. }
    143. //创建桶
    144. public static String createBucket(Map map){
    145. String http = "https://";
    146. // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
    147. String endpoint = map.get("domain").toString();
    148. // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    149. String accessKeyId = map.get("accessKeyId").toString();
    150. String accessKeySecret = map.get("accessKeySecret").toString();
    151. // 填写Bucket名称,例如examplebucket。
    152. String bucketName = map.get("bucketName").toString();
    153. // 创建OSSClient实例。
    154. OSS ossClient = new OSSClientBuilder().build(http+endpoint, accessKeyId, accessKeySecret);
    155. try {
    156. // 创建CreateBucketRequest对象。
    157. CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
    158. // 如果创建存储空间的同时需要指定存储类型和数据容灾类型, 请参考如下代码。
    159. // 此处以设置存储空间的存储类型为标准存储为例介绍。
    160. createBucketRequest.setStorageClass(StorageClass.Standard);
    161. // 数据容灾类型默认为本地冗余存储,即DataRedundancyType.LRS。如果需要设置数据容灾类型为同城冗余存储,请设置为DataRedundancyType.ZRS。
    162. //createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS);
    163. // 设置存储空间的权限为公共读,默认为私有。
    164. createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
    165. // 创建存储空间。
    166. ossClient.createBucket(createBucketRequest);
    167. } catch (OSSException oe) {
    168. System.out.println("Caught an OSSException, which means your request made it to OSS, "
    169. + "but was rejected with an error response for some reason.");
    170. System.out.println("Error Message:" + oe.getErrorMessage());
    171. System.out.println("Error Code:" + oe.getErrorCode());
    172. System.out.println("Request ID:" + oe.getRequestId());
    173. System.out.println("Host ID:" + oe.getHostId());
    174. } catch (ClientException ce) {
    175. System.out.println("Caught an ClientException, which means the client encountered "
    176. + "a serious internal problem while trying to communicate with OSS, "
    177. + "such as not being able to access the network.");
    178. System.out.println("Error Message:" + ce.getMessage());
    179. } finally {
    180. if (ossClient != null) {
    181. ossClient.shutdown();
    182. }
    183. }
    184. System.out.println(">>>>>>>>>>>>>>>新创建桶的名称:" + bucketName);
    185. return bucketName;
    186. }
    187. //本地上传文件
    188. public static String fileLocalUpload(Map map) {
    189. // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
    190. String http = "https://";
    191. String endpoint = map.get("domain").toString();//"oss-cn-beijing.aliyuncs.com";
    192. // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    193. String accessKeyId = map.get("accessKeyId").toString();//"55RnyDZ";
    194. String accessKeySecret = map.get("accessKeySecret").toString();//"Aui2oVSG";
    195. // 填写Bucket名称,例如examplebucket。
    196. String bucketName = map.get("bucketName").toString();//"ddndl";
    197. //获取原文件名
    198. String filePath = map.get("filePath").toString();;
    199. //获取文件后缀
    200. String suffixName = filePath.substring(filePath.lastIndexOf("."));
    201. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
    202. String objectName = "pdd_video/"+ UUID.randomUUID()+suffixName;
    203. //String filePath = ;//"C:\\Users\\Administrator\\Desktop\\a02604f5cd493125abdf2cfcae98d2c1.mp4.f30.mp4";
    204. // 创建OSSClient实例。
    205. OSS ossClient = new OSSClientBuilder().build(http+endpoint, accessKeyId, accessKeySecret);
    206. PutObjectResult objectResult ;
    207. try {
    208. InputStream inputStream = new FileInputStream(filePath);
    209. // 创建PutObject请求。
    210. objectResult = ossClient.putObject(bucketName, objectName, inputStream);
    211. } catch (Exception e) {
    212. System.out.println("Error Message:" + e.getMessage());
    213. throw new ServiceException("文件上传失败:"+e.getMessage());
    214. } finally {
    215. if (ossClient != null) {
    216. ossClient.shutdown();
    217. }
    218. }
    219. String fileUrl = http+bucketName+"."+ endpoint+"/"+objectName;
    220. System.out.println(">>>>>>>>>>>>>>>>> 上传文件后的url:"+fileUrl);
    221. return fileUrl;
    222. }
    223. //根据OSS图片url得到缩略图url
    224. public static String getThumbnailUrl(String imgUrl){
    225. imgUrl = imgUrl + "?x-oss-process=image/resize,m_fill,w_400,quality,q_60";
    226. System.out.println(">>>>>>>>>>>>>>>>> 缩略图url:"+imgUrl);
    227. return imgUrl;
    228. }
    229. //根据OSS视频url得到视频封面图url
    230. public static String getVideoCoverlUrl(String videoUrl){
    231. videoUrl = videoUrl + "?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast";
    232. System.out.println(">>>>>>>>>>>>>>>>> 视频封面图url:"+videoUrl);
    233. return videoUrl;
    234. }
    235. }

    maven  pom需引入的jar

    
    
        com.aliyun.oss
        aliyun-sdk-oss
        3.10.2
    
  • 相关阅读:
    猫12分类:使用yolov5训练检测模型
    【linux/docker】解决ORA-28000: the account is locked
    Redis:StringRedisTemplate简介
    semaphere部署,配置ldap
    Qt之Model/View架构
    JAVA深化篇_42—— 正则表达式
    RocketMq简介及安装、docker安装rocketmq、安装rocketmq可视化管理端
    apt-get手册翻译
    MySQL innoDB 间隙锁产生的死锁问题
    Accelerate 0.24.0文档 三:超大模型推理(内存估算、Sharded checkpoints、bitsandbytes量化、分布式推理)
  • 原文地址:https://blog.csdn.net/yyongsheng/article/details/126902273