巴拉巴拉
小魔仙

阿里云 OSS 工具

之前的一篇博文中,有一篇是介绍oss整合到spring里面的介绍。

现在吧这个工具单独拿了出来并不需要利用spring能单独使用的一个util工具类,即使是使用spring也一样可以简单方便的使用这个工具类。

之前的文章:AliyunOSS整合Spring的一些简单操作。

这个老版本已经不推荐大家参考,仅做记录使用,请参考本文文章内容。

在这个基础上改了一部分代码,并且加了一些基础功能,例如清空某个目录,得到某个目录下的所有key,对key进行重命名,获取oss中文件对象的md5编码,等等。

package com.againfly.util.aliyun;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.againfly.dex.util.Const;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;

/**
 * 
 * @ClassName: OssUtil
 * @Description: Oss操作工具类
 * @author Jecced
 * @date 2017年7月24日 下午3:11:01
 *
 */
public class OssUtil {
	
	private static Logger logger = LoggerFactory.getLogger(OssUtil.class);
	
	/* ***你的阿里云Access Key Id*** */
	private static String accessKeyId = "***你的阿里云Access Key Id***";
	/* ***你的阿里云Access Key Secret*** */
	private static String accessKeySecret = "***你的阿里云Access Key Secret***";
	/* ***你的阿里云OSS BuckName*** */
	private static String bucketName = "BuckName";
	/* ***你的阿里云OSS 所属地区EndPoint*** */
	private static String ossEndpoint = "oss-cn-hangzhou.aliyuncs.com";
	/* ***你的阿里云OSS 对应绑定BuckName的域名,如果没有绑定请设置为null *** */
	private static String bindDomin = "http://oss.demo.com";
	private static int timeout = 5000;
	
	private static OSSClient ossClient;
	
	static {
	    init();
	}
	
	public static synchronized void init() {
	    if(ossClient != null){
	        return;
	    }
		ClientConfiguration conf = new ClientConfiguration();
		conf.setConnectionTimeout(timeout);
		conf.setConnectionRequestTimeout(timeout);
		conf.setSocketTimeout(timeout);
		conf.setMaxErrorRetry(10);
		ossClient = new OSSClient("http://" + ossEndpoint, accessKeyId, accessKeySecret, conf);
		
		if(null != bindDomin && bindDomin.startsWith("http")){
            if(!bindDomin.endsWith("/")){
                bindDomin += "/";
            }
        }else{
            bindDomin = "http://" + bucketName + "." + ossEndpoint + "/";
        }
		logger.info("oss init");
	}
	
	public static void destroy() {
	    if(ossClient != null){
	        ossClient.shutdown();
	        ossClient = null;
	        logger.info("oss destory");
	    }
	}

	/**
	 * @Title: isExist
	 * @Description: 判断key是否存在
	 * @author Jecced
	 * @param key
	 * @return
	 */
	public static boolean isExist(String key) {
		key = formatKey(key);
		return ossClient.doesObjectExist(bucketName, key);
	}
	
	/**
	 * @Title: getSimplePutMD5
	 * @Description: 获取key文件的md5
	 * @author Jecced
	 * @param key
	 * @return
	 */
	public static String getSimplePutMD5(String key){
		key = formatKey(key);
		boolean exists = isExist(key);
		if(exists){
			OSSObject object = ossClient.getObject(bucketName, key);
			ObjectMetadata meta = object.getObjectMetadata();
			String eTag = meta.getETag();
			return eTag;
		}
		return "";
	}
	
	/**
	 * @Title: getFileSize
	 * @Description: 获取文件大小
	 * @author Jecced
	 * @param key
	 * @return
	 */
	public static long getFileSize(String key){
		key = formatKey(key);
		if(isExist(key)){
			OSSObject object = ossClient.getObject(bucketName, key);
			ObjectMetadata metadata = object.getObjectMetadata();
			long contentLength = metadata.getContentLength();
			return contentLength;
		}
		return -1;
	}

	/**
	 * @Title: getObjeInputStream
	 * @Description: 从OSS中获取对象输入流
	 * @author Jecced
	 * @param key
	 * @return
	 */
	public static InputStream getObjeInputStream(String key) {
		key = formatKey(key);
		if(!isExist(key)){
			return null;
		}
		OSSObject obj = ossClient.getObject(bucketName, key);
		return obj.getObjectContent();
	}

	/**
	 * @Title: downObj
	 * @Description: 文件下载到指定File对象
	 * @author Jecced
	 * @param key
	 * @param file
	 */
	public static void downObj(String key, File file) {
		key = formatKey(key);
		InputStream is = getObjeInputStream(key);
		
		FileOutputStream fos = null;
		try{
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024 * 10];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.safeClose(fos);
            IOUtils.safeClose(is);
        }
	}

	/**
	 * 简单上传OSS文件 
	 * @param name 文件名
	 * @param file File对象
	 * @param path 存储路径
	 * @param contentType 手动设置文件类型:image/png
	 * @return OSS文件Key的路径
	 */
	public static String uploadObj(String path, String name, File file, String contentType) {
		String key = path + "/" + name;
		key = formatKey(key);
		ObjectMetadata meta = null;
		if (contentType != null) {
			meta = new ObjectMetadata();
			meta.setContentType(contentType);
		}
		ossClient.putObject(bucketName, key, file, meta);

		return bindDomin + key;
	}

	/**
	 * @Description: uploadStream 上传一个is流
	 * @author Jecced
	 * @param path     oss路径
	 * @param name     文件名
	 * @param is       is输入流
	 * @param contentType 手动设置文件类型:image/png
	 * @return
	 */
	public static String uploadStream(String path, String name, InputStream is, String contentType) {
		String key = path + "/" + name;
		key = formatKey(key);
		ObjectMetadata meta = null;
		if (contentType != null) {
			meta = new ObjectMetadata();
			meta.setContentType(contentType);
		}
		ossClient.putObject(bucketName, key, is, meta);
		return bindDomin + key;
	}

	/**
	 * @Title: uploadObj
	 * @Description: 上传一个文件,简单上传
	 * @author Jecced
	 * @param 路径
	 * @param 文件名
	 * @param 文件对象
	 * @return
	 */
	public static String uploadObj(String path, String name, File file) {
		return uploadObj(path, name, file, null);
	}

	/**
	 * 删除指定key
	 */
	public static void delKey(String key) {
		ossClient.deleteObject(bucketName, key);
	}

	/**
	 * 格式化key的格式
	 */
	private static String formatKey(String key) {
	    if(!key.startsWith("/") && -1 == key.indexOf('\\')){
	        return key;
	    }
		if (key != null) {
			key = key.replaceAll("\\\\", "/");
		}
		while (key != null && key.startsWith("/")) {
			key = key.substring(1, key.length());
		}
		return key;
	}
	
	/**
	 * 根据url格式化得到key
	 */
	public static String UrlParseKey(String url){
		try{
			return url.substring(url.indexOf('/', 7) + 1);
		}catch (Exception e) {
			return "";
		}
	}
	
	/**
	 * 根据key,url获取文件名
	 */
	public static String getFileName(String key){
		return key.substring(key.lastIndexOf('/') + 1);
	}
	
	/**
	 * @Title: rename
	 * @Description: oss key重命名
	 * @author Jecced
	 * @param oldKey
	 * @param newKey
	 * @return
	 */
	public static boolean rename(String oldKey, String newKey){
		oldKey = formatKey(oldKey);
		newKey = formatKey(newKey);
		if(!isExist(oldKey)){
			return false;
		}
		if(isExist(newKey)){
			return false;
		}
		ossClient.copyObject(bucketName, oldKey, bucketName, newKey);
		ossClient.deleteObject(bucketName, oldKey);
		return true;
	}
	
	/**
	 * @Title: listKey
	 * @Description: 遍历迭代出路径中的所有key
	 * @author Jecced
	 * @param path 路径,前缀
	 */
	public static List<String> listKey(String path){
	    List<String> list = new ArrayList<>();
	    String nextMarker = null;
        ObjectListing objectListing = null;
        List<OSSObjectSummary> sums = null;
        do {
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            listObjectsRequest.withMarker(nextMarker)
                .withMaxKeys(1000)//每次最大返回复合条件的对象,最大1000
                .setPrefix(path);
            objectListing = ossClient.listObjects(listObjectsRequest);
            sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                list.add(s.getKey());
            }
            nextMarker = objectListing.getNextMarker();
        } while (objectListing.isTruncated());
        return list;
	}
	
	/**
	 * @Title: delKeys
	 * @Description: 删除指定的所有key
	 * @author Jecced
	 * @param keys 所有要被删除的key集合
	 */
	public static void delKeys(List<String> keys){
	    DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(
                new DeleteObjectsRequest(bucketName).withKeys(keys));
        deleteObjectsResult.getDeletedObjects();
	}
	
	/**
	 * @Title: cleanPath
	 * @Description: 删除/清空一整个路径内的所有文件
	 * @author Jecced
	 * @param path
	 */
	public static void cleanPath(String path){
	    List<String> keys = listKey(path);
	    delKeys(keys);
	}

}

 

赞(0) 打赏
如果文章对你有帮助,欢迎你来评价反馈。AgainFly » 阿里云 OSS 工具
标签:

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  • Q Q(选填)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏