https://blog.csdn.net/github_36086968/article/details/53113274

本篇文章希望你先看完官方的API了解一下OSS基本语法和概念再来应该比较容易懂。

  • 这里给出官方的OSS API:OSS API
  • 官方SDK:点击打开链接
  • 官方帮助文档:点击打开链接
  • OSS GitHub地址:点击打开链接
  • OSS java 依赖jar包地址:点击下载
1.首先确保你已经注册并开通了OSS服务,并在控制台建立好了bucket,并获取到了accessKeyId和accessKeySecret
2.创建一个配置文件,里面存放OSS需要的endpoit和一些以后可能会改定的配置。
config.properties:
[plain]  view plain  copy
  1. #阿里云OSS配置
  2. endpoint = http://oss-cn-shenzhen.aliyuncs.com     //可以选择其他的地址
  3. bucketName = ft-pic                                //已经在控制台创建的bucket
  4. picLocation = CDoc/cms/                            //你上传文件的保存路径,如果bucket中不存在则创建(其实原理并不是文件夹,只是文件名,详情请先阅读官方文档)
  5. accessKeyId = ***********                          //相应的id和key值,请填写你具体的值,这里不方便展示我自己的。
  6. accessKeySecret = ************
3.创建一个读取配置文件的工具类,这并不是必须的,你可以按照自己的方式来实现配置的调取
SystemConfig.java:
[java]  view plain  copy
  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.util.Properties;
  4. /**
  5. * 读取后缀名为“.properties”的文件
  6. * @author
  7. *
  8. */
  9. public class SystemConfig {
  10. private static final String CONFIG_PROPERTIES="config.properties";
  11. public static String getConfigResource(String key) throws IOException{
  12. ClassLoader loader = Thread.currentThread().getContextClassLoader();
  13. Properties properties = new Properties();
  14. InputStream in = loader.getResourceAsStream(CONFIG_PROPERTIES);
  15. properties.load(in);
  16. String value = properties.getProperty(key);
  17. // 编码转换,从ISO-8859-1转向指定编码
  18. value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
  19. in.close();
  20. return value;
  21. }
  22. }

4.创建一个OSS配置类,用来方便的获取基本信息。

OSSConfig.java:
[java]  view plain  copy
  1. /**
  2. * @ClassName: OSSConfig
  3. * @Description: OSS配置类
  4. * @author AggerChen
  5. * @date 2016年11月4日 下午3:58:36
  6. */
  7. class OSSConfig{
  8. private  String endpoint;       //连接区域地址
  9. private  String accessKeyId;    //连接keyId
  10. private  String accessKeySecret;    //连接秘钥
  11. private  String bucketName;     //需要存储的bucketName
  12. private  String picLocation;    //图片保存路径
  13. public OSSConfig() {
  14. try {
  15. this.endpoint = SystemConfig.getConfigResource("endpoint");
  16. this.bucketName = SystemConfig.getConfigResource("bucketName");
  17. this.picLocation = SystemConfig.getConfigResource("picLocation");
  18. this.accessKeyId = SystemConfig.getConfigResource("accessKeyId");
  19. this.accessKeySecret = SystemConfig.getConfigResource("accessKeySecret");
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. public String getEndpoint() {
  25. return endpoint;
  26. }
  27. public void setEndpoint(String endpoint) {
  28. this.endpoint = endpoint;
  29. }
  30. public String getAccessKeyId() {
  31. return accessKeyId;
  32. }
  33. public void setAccessKeyId(String accessKeyId) {
  34. this.accessKeyId = accessKeyId;
  35. }
  36. public String getAccessKeySecret() {
  37. return accessKeySecret;
  38. }
  39. public void setAccessKeySecret(String accessKeySecret) {
  40. this.accessKeySecret = accessKeySecret;
  41. }
  42. public String getBucketName() {
  43. return bucketName;
  44. }
  45. public void setBucketName(String bucketName) {
  46. this.bucketName = bucketName;
  47. }
  48. public String getPicLocation() {
  49. return picLocation;
  50. }
  51. public void setPicLocation(String picLocation) {
  52. this.picLocation = picLocation;
  53. }
  54. }

5.编写OSS上传工具类

OSSUploadUtil.java:
[java]  view plain  copy
  1. package com.fortis.cms.utils;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.UUID;
  10. import com.aliyun.oss.ClientException;
  11. import com.aliyun.oss.OSSClient;
  12. import com.aliyun.oss.OSSException;
  13. import com.aliyun.oss.model.DeleteObjectsRequest;
  14. import com.aliyun.oss.model.DeleteObjectsResult;
  15. import com.aliyun.oss.model.GenericRequest;
  16. import com.aliyun.oss.model.ObjectMetadata;
  17. import com.aliyun.oss.model.PutObjectRequest;
  18. /**
  19. *
  20. * @ClassName: OSSUploadUtil
  21. * @Description: 阿里云OSS文件上传工具类
  22. * @author AggerChen
  23. * @date 2016年11月3日 下午12:03:24
  24. */
  25. public class OSSUploadUtil {
  26. private static OSSConfig config = null;
  27. /**
  28. *
  29. * @MethodName: uploadFile
  30. * @Description: OSS单文件上传
  31. * @param file
  32. * @param fileType 文件后缀
  33. * @return String 文件地址
  34. */
  35. public static String uploadFile(File file,String fileType){
  36. config = config==null?new OSSConfig():config;
  37. String fileName = config.getPicLocation()+UUID.randomUUID().toString().toUpperCase().replace("-", "")+"."+fileType; //文件名,根据UUID来
  38. return putObject(file,fileType,fileName);
  39. }
  40. /**
  41. *
  42. * @MethodName: updateFile
  43. * @Description: 更新文件:只更新内容,不更新文件名和文件地址。
  44. *      (因为地址没变,可能存在浏览器原数据缓存,不能及时加载新数据,例如图片更新,请注意)
  45. * @param file
  46. * @param fileType
  47. * @param oldUrl
  48. * @return String
  49. */
  50. public static String updateFile(File file,String fileType,String oldUrl){
  51. String fileName = getFileName(oldUrl);
  52. if(fileName==null) return null;
  53. return putObject(file,fileType,fileName);
  54. }
  55. /**
  56. *
  57. * @MethodName: replaceFile
  58. * @Description: 替换文件:删除原文件并上传新文件,文件名和地址同时替换
  59. *      解决原数据缓存问题,只要更新了地址,就能重新加载数据)
  60. * @param file
  61. * @param fileType 文件后缀
  62. * @param oldUrl 需要删除的文件地址
  63. * @return String 文件地址
  64. */
  65. public static String replaceFile(File file,String fileType,String oldUrl){
  66. boolean flag = deleteFile(oldUrl);      //先删除原文件
  67. if(!flag){
  68. //更改文件的过期时间,让他到期自动删除。
  69. }
  70. return uploadFile(file, fileType);
  71. }
  72. /**
  73. *
  74. * @MethodName: deleteFile
  75. * @Description: 单文件删除
  76. * @param fileUrl 需要删除的文件url
  77. * @return boolean 是否删除成功
  78. */
  79. public static boolean deleteFile(String fileUrl){
  80. config = config==null?new OSSConfig():config;
  81. String bucketName = OSSUploadUtil.getBucketName(fileUrl);       //根据url获取bucketName
  82. String fileName = OSSUploadUtil.getFileName(fileUrl);           //根据url获取fileName
  83. if(bucketName==null||fileName==null) return false;
  84. OSSClient ossClient = null;
  85. try {
  86. ossClient = new OSSClient(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
  87. GenericRequest request = new DeleteObjectsRequest(bucketName).withKey(fileName);
  88. ossClient.deleteObject(request);
  89. } catch (Exception oe) {
  90. oe.printStackTrace();
  91. return false;
  92. } finally {
  93. ossClient.shutdown();
  94. }
  95. return true;
  96. }
  97. /**
  98. *
  99. * @MethodName: batchDeleteFiles
  100. * @Description: 批量文件删除(较快):适用于相同endPoint和BucketName
  101. * @param fileUrls 需要删除的文件url集合
  102. * @return int 成功删除的个数
  103. */
  104. public static int deleteFile(List<String> fileUrls){
  105. int deleteCount = 0;    //成功删除的个数
  106. String bucketName = OSSUploadUtil.getBucketName(fileUrls.get(0));       //根据url获取bucketName
  107. List<String> fileNames = OSSUploadUtil.getFileName(fileUrls);         //根据url获取fileName
  108. if(bucketName==null||fileNames.size()<=0) return 0;
  109. OSSClient ossClient = null;
  110. try {
  111. ossClient = new OSSClient(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
  112. DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName).withKeys(fileNames);
  113. DeleteObjectsResult result = ossClient.deleteObjects(request);
  114. deleteCount = result.getDeletedObjects().size();
  115. } catch (OSSException oe) {
  116. oe.printStackTrace();
  117. throw new RuntimeException("OSS服务异常:", oe);
  118. } catch (ClientException ce) {
  119. ce.printStackTrace();
  120. throw new RuntimeException("OSS客户端异常:", ce);
  121. } finally {
  122. ossClient.shutdown();
  123. }
  124. return deleteCount;
  125. }
  126. /**
  127. *
  128. * @MethodName: batchDeleteFiles
  129. * @Description: 批量文件删除(较慢):适用于不同endPoint和BucketName
  130. * @param fileUrls 需要删除的文件url集合
  131. * @return int 成功删除的个数
  132. */
  133. public static int deleteFiles(List<String> fileUrls){
  134. int count = 0;
  135. for (String url : fileUrls) {
  136. if(deleteFile(url)){
  137. count++;
  138. }
  139. }
  140. return count;
  141. }
  142. /**
  143. *
  144. * @MethodName: putObject
  145. * @Description: 上传文件
  146. * @param file
  147. * @param fileType
  148. * @param fileName
  149. * @return String
  150. */
  151. private static String putObject(File file,String fileType,String fileName){
  152. config = config==null?new OSSConfig():config;
  153. String url = null;      //默认null
  154. OSSClient ossClient = null;
  155. try {
  156. ossClient = new OSSClient(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
  157. InputStream input = new FileInputStream(file);
  158. ObjectMetadata meta = new ObjectMetadata();             // 创建上传Object的Metadata
  159. meta.setContentType(OSSUploadUtil.contentType(fileType));       // 设置上传内容类型
  160. meta.setCacheControl("no-cache");                   // 被下载时网页的缓存行为
  161. PutObjectRequest request = new PutObjectRequest(config.getBucketName(), fileName,input,meta);           //创建上传请求
  162. ossClient.putObject(request);
  163. url = config.getEndpoint().replaceFirst("http://","http://"+config.getBucketName()+".")+"/"+fileName;       //上传成功再返回的文件路径
  164. } catch (OSSException oe) {
  165. oe.printStackTrace();
  166. return null;
  167. } catch (ClientException ce) {
  168. ce.printStackTrace();
  169. return null;
  170. } catch (FileNotFoundException e) {
  171. e.printStackTrace();
  172. return null;
  173. } finally {
  174. ossClient.shutdown();
  175. }
  176. return url;
  177. }
  178. /**
  179. *
  180. * @MethodName: contentType
  181. * @Description: 获取文件类型
  182. * @param FileType
  183. * @return String
  184. */
  185. private static String contentType(String fileType){
  186. fileType = fileType.toLowerCase();
  187. String contentType = "";
  188. switch (fileType) {
  189. case "bmp": contentType = "image/bmp";
  190. break;
  191. case "gif": contentType = "image/gif";
  192. break;
  193. case "png":
  194. case "jpeg":
  195. case "jpg": contentType = "image/jpeg";
  196. break;
  197. case "html":contentType = "text/html";
  198. break;
  199. case "txt": contentType = "text/plain";
  200. break;
  201. case "vsd": contentType = "application/vnd.visio";
  202. break;
  203. case "ppt":
  204. case "pptx":contentType = "application/vnd.ms-powerpoint";
  205. break;
  206. case "doc":
  207. case "docx":contentType = "application/msword";
  208. break;
  209. case "xml":contentType = "text/xml";
  210. break;
  211. case "mp4":contentType = "video/mp4";
  212. break;
  213. default: contentType = "application/octet-stream";
  214. break;
  215. }
  216. return contentType;
  217. }
  218. /**
  219. *
  220. * @MethodName: getBucketName
  221. * @Description: 根据url获取bucketName
  222. * @param fileUrl 文件url
  223. * @return String bucketName
  224. */
  225. private static String getBucketName(String fileUrl){
  226. String http = "http://";
  227. String https = "https://";
  228. int httpIndex = fileUrl.indexOf(http);
  229. int httpsIndex = fileUrl.indexOf(https);
  230. int startIndex  = 0;
  231. if(httpIndex==-1){
  232. if(httpsIndex==-1){
  233. return null;
  234. }else{
  235. startIndex = httpsIndex+https.length();
  236. }
  237. }else{
  238. startIndex = httpIndex+http.length();
  239. }
  240. int endIndex = fileUrl.indexOf(".oss-");
  241. return fileUrl.substring(startIndex, endIndex);
  242. }
  243. /**
  244. *
  245. * @MethodName: getFileName
  246. * @Description: 根据url获取fileName
  247. * @param fileUrl 文件url
  248. * @return String fileName
  249. */
  250. private static String getFileName(String fileUrl){
  251. String str = "aliyuncs.com/";
  252. int beginIndex = fileUrl.indexOf(str);
  253. if(beginIndex==-1) return null;
  254. return fileUrl.substring(beginIndex+str.length());
  255. }
  256. /**
  257. *
  258. * @MethodName: getFileName
  259. * @Description: 根据url获取fileNames集合
  260. * @param fileUrl 文件url
  261. * @return List<String>  fileName集合
  262. */
  263. private static List<String> getFileName(List<String> fileUrls){
  264. List<String> names = new ArrayList<>();
  265. for (String url : fileUrls) {
  266. names.add(getFileName(url));
  267. }
  268. return names;
  269. }
  270. }

6.调用测试,OSSUploadUtil工具类对外只提供了几个方法:

OSSUploadUtil.uploadFile(File file, String fileType)  //单文件上传,type:文件后缀名
OSSUploadUtil.updateFile(File file, String fileType, String oldUrl) //更新文件:只更新内容,不更新文件名和文件地址。
OSSUploadUtil.replaceFile(File file, String fileType, String oldUrl) //替换文件,删除源文件并上传新文件,文件名和地址也改变
OSSUploadUtil.deleteFile(List<String> fileUrls)  //删除多文件,根据问价url来自定获取其中的bucket和文件名,用于bucket和文件名可能存在不同的,循环调用 deleteFile方法
OSSUploadUtil.deleteFile(String fileUrl) //删除单文件
OSSUploadUtil.deleteFiles(List<String> fileUrls)  //删除多文件,根据配置直接取删除多个文件,bucket和文件地址从配置中获取,用于多文件bucket和文件名都相同的
总结:
  1. 本例只是简单的运用,当然还有更高级的应用暂时还没有研究,希望以后有空再分享出来。
  2. 其中很多例子,在官方的SDK中都有,本文只是展示了对于我这里适用的方式,其他的多种配置方式请参考官方文档。
  3. 如有问题,可以提出,希望能够交流和共同学习。
  4. 本文示例皆为原创,转载请注明出处。

阿里云OSS存储基于JAVA基本使用相关推荐

  1. 从AWS S3换成阿里云OSS存储所踩的坑

    因业务需要,AWS S3 不能使用了,要换成阿里云OSS存储和下载.简单作以记录,以作备忘. 1.参照https://help.aliyun.com/product/31815.html?spm=51 ...

  2. 七牛云和阿里云OSS存储图片服务器使用

    目录 1 图片存储方案 1.1 介绍 1.2 七牛云存储 1.2.1 注册.登录 1.2.2 新建存储空间 1.2.3 查看存储空间信息 1.2.4 开发者中心 1.2.5 鉴权 1.2.6 Java ...

  3. mysql数据库备份到oss_备份MySQL数据库并上传到阿里云OSS存储

    1. 环境配置 要将本地文件上传到阿里云oss中, 必须使用阿里云提供的工具 ossutil, 有32位,也有64位的, Linux和Windows都有.具体可以到阿里云官网下载 本文以Linux系统 ...

  4. django图片上传到oss_django 配置阿里云OSS存储media文件的例子

    1. 安装django-aliyun-oss2-storage包 linux上用 pip install django-aliyun-oss2-storage 无报错,顺利安装 windows上报错: ...

  5. 前端(react)上传到阿里云OSS存储 实例

    需求背景 由于现有的后台管理系统,上传的视频越来越大,加上上传视频较慢,后端小哥提出直接从前端上传视频或者其他文件到阿里云OSS存储. 阿里云OSS 阿里云OSS文档介绍,这里不做过多赘述 安装 原本 ...

  6. 分布式文件存储——阿里云oss存储

    阿里云oss存储 目录 阿里云oss存储 获取设置参数 实现上传.下载方法 设置生命周期 获取设置参数 bucket名 endpoit key secret package configconst ( ...

  7. tp5.0阿里云oss存储Demo

    序言:最近在做一个项目,关于的是投稿的项目,其实就是一个图片网站的问题,原本做的一直是将文件存放到服务器中,但现在由于用户越来越多,所以要将图片的路径更新到一个位置,所以阿里云oss存储就出来了. 首 ...

  8. 阿里云oss 使用, 基于Nginx 配置云服务器+oss的内网访问 , 及使用Java SDK 完成上传,下载,删除,查询文件列表操作

    一.同阿里产品,云服务器和存储对象oss-配置内网访问 阿里存储对象oss 地址: https://oss.console.aliyun.com/overview 配置须知 通过Nginx 进行网络转 ...

  9. JAVA通过阿里云OSS存储实现图片上传功能

    一.前置准备 首先我们需要在阿里云注册账号,实名认证后开通OSS功能,点击进入OSS功能的管理平台 进入概览页面后,点击Bucket列表,创建一个Bucket(相当于一个存放文件的文件夹)  关键是要 ...

最新文章

  1. fscanf()函数具体解释
  2. Linux下undefined reference to ‘pthread_create’问题解决
  3. 【数据挖掘笔记十】聚类分析:基本概念和方法
  4. Java的工厂模式(三)
  5. 编写Linux内核模块——第一部分:前言
  6. linux_bash_shell_cheat_sheet(自译)
  7. centos7安装python3_详解Centos7升级python 2.7至Python 3.7
  8. 高可用之2——存储b
  9. Openproj 在64位操作系统报错errno=193
  10. 【渝粤教育】广东开放大学 企业财务报表分析 形成性考核 (26)
  11. 5月6阴阳师服务器维护,阴阳师正式服5月6日更新公告
  12. 乐高机器人走进图书馆活动方案_欢迎参加“乐高机器人创意搭建赛”活动
  13. verilog二分频代码verilog三分频代码
  14. 随机模拟在多排服务器上的应用,在Excel中应用随机函数模拟多服务台单队列排队系统...
  15. 爬虫学习日记1-豆瓣top250电影信息爬取
  16. JavaScript中pageX pageY offsetX offsetY区别
  17. $‘\r‘: command not found,syntax error near unexpected token `$‘in\r‘‘
  18. 在Delphi中打印条码的方法步骤如下
  19. android sdk版本
  20. Thinkcmf子栏目获取父级栏目所有子栏目列表

热门文章

  1. 西安海棠职业学院计算机考试,考计算机的同学,你们懂得~
  2. pandas 文档自用3
  3. 2022-2028全球与中国内存测试设备市场现状及未来发展趋势
  4. 调度算法先来先服务(FCFS)、最短作业优先(SJF)和最高响应比优先(HRRN)算法
  5. thead java_Java中多线程的使用(超级超级详细) Thead类的使用 3
  6. Docker Compose的安装与使用
  7. win10系统出现打开文件被拒绝访问的问题
  8. 花开记春,花落记秋,早已忘却岁月悠悠。曲终人散,花亦垂首,空留旧人昔日颜容。
  9. springboot 使用 @Scheduled注解定时任务, 方法传参解决办法
  10. NetCMS修改之四:扩展轮换幻灯片属性(NorFilt),具有导读显示