oss存储

前段时间公司让研究阿里云OSS,说计划会用起来。OSS就是一个阿里提供的在线存储服务,其实原先公司自己搭建的文件服务器也就能用,不过可能是为了以后的业务扩大着想,让提前研究使用了。OSS的基本概念他官网上有很多资料,我这里也就不再说了。研究了一整子,整理了一些方法,所以这里记录出来。本人是小白一枚,一下的知识竟可能的浅显,但也是我自己研究使用的思路,开始也没有找到一篇全面的使用手册,因为官方的SDK也是简洁的不能再简洁了。

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

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. /** 
  6.  * 读取后缀名为“.properties”的文件 
  7.  * @author  
  8.  * 
  9.  */  
  10. public class SystemConfig {  
  11.       
  12.     private static final String CONFIG_PROPERTIES="config.properties";  
  13.   
  14.     public static String getConfigResource(String key) throws IOException{  
  15.         ClassLoader loader = Thread.currentThread().getContextClassLoader();  
  16.         Properties properties = new Properties();  
  17.         InputStream in = loader.getResourceAsStream(CONFIG_PROPERTIES);  
  18.         properties.load(in);  
  19.         String value = properties.getProperty(key);  
  20.         // 编码转换,从ISO-8859-1转向指定编码  
  21.         value = new String(value.getBytes("ISO-8859-1"), "UTF-8");  
  22.         in.close();  
  23.         return value;  
  24.     }  
  25. }  

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.       
  14.     public OSSConfig() {  
  15.         try {  
  16.             this.endpoint = SystemConfig.getConfigResource("endpoint");  
  17.             this.bucketName = SystemConfig.getConfigResource("bucketName");  
  18.             this.picLocation = SystemConfig.getConfigResource("picLocation");  
  19.             this.accessKeyId = SystemConfig.getConfigResource("accessKeyId");  
  20.             this.accessKeySecret = SystemConfig.getConfigResource("accessKeySecret");  
  21.         } catch (IOException e) {  
  22.             e.printStackTrace();  
  23.         }  
  24.     }  
  25.   
  26.     public String getEndpoint() {  
  27.         return endpoint;  
  28.     }  
  29.     public void setEndpoint(String endpoint) {  
  30.         this.endpoint = endpoint;  
  31.     }  
  32.     public String getAccessKeyId() {  
  33.         return accessKeyId;  
  34.     }  
  35.     public void setAccessKeyId(String accessKeyId) {  
  36.         this.accessKeyId = accessKeyId;  
  37.     }  
  38.     public String getAccessKeySecret() {  
  39.         return accessKeySecret;  
  40.     }  
  41.     public void setAccessKeySecret(String accessKeySecret) {  
  42.         this.accessKeySecret = accessKeySecret;  
  43.     }  
  44.     public String getBucketName() {  
  45.         return bucketName;  
  46.     }  
  47.     public void setBucketName(String bucketName) {  
  48.         this.bucketName = bucketName;  
  49.     }  
  50.     public String getPicLocation() {  
  51.         return picLocation;  
  52.     }  
  53.     public void setPicLocation(String picLocation) {  
  54.         this.picLocation = picLocation;  
  55.     }  
  56. }  

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

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. 本文示例皆为原创,转载请注明出处。
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值