Newer
Older
huludao / src / main / java / com / newfiber / api / pc / controller / News / COSClientManager.java
package com.newfiber.api.pc.controller.News;

import com.newfiber.api.core.utils.UUIDUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.Copy;
import com.qcloud.cos.transfer.TransferManager;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class COSClientManager {

	private String secretId = "AKIDDF2OXSLr31jTIxDvKVP5ZnlbFdkbr3uV";
	private String secretKey = "6nHXYgZB1aeaFdkQr1vOcZYGuJUSs41i";
	private String appid = "1257985062";
	private COSClient cosClient = null;
	private String bucketNamePublic = "";
	private String imageDir = "/newfiber-river/image/";// 存放文件的目录
	private TransferManager transferManager;
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

	private COSClientManager() {
		init();
	}

	private void init() {
		bucketNamePublic = "nf" + "-" + appid;
		COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

		// 2 设置bucket的区域, COS地域的简称请参照
		// https://cloud.tencent.com/document/product/436/6224
		ClientConfig clientConfig = new ClientConfig(new Region("ap-chengdu"));
		// 3 生成cos客户端
		cosClient = new COSClient(cred, clientConfig);

		ExecutorService threadPool = Executors.newFixedThreadPool(1);
		// 传入一个threadpool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池。
		transferManager = new TransferManager(cosClient, threadPool);

	}
	private static class COSClientManagerHandle {
		private static COSClientManager instance = new COSClientManager();
	}

	public static COSClientManager getInstance() {
		return COSClientManagerHandle.instance;
	}

	/**
	 * 创建
	 * 
	 * @param bucketName
	 * @return
	 */
	public Bucket createBucket(String bucketName) {
		bucketName = bucketName + "-" + appid;
		return cosClient.createBucket(bucketName);
	}

	/**
	 * 上传文件
	 * 
	 * @param key
	 * @param file
	 * @return
	 * @throws CosClientException
	 * @throws CosServiceException
	 */
	public PutObjectResult putObject(String key, File file) throws CosClientException, CosServiceException {
		String bucketName = bucketNamePublic;
		return cosClient.putObject(bucketName, key, file);
	}

	/**
	 * 输入流上传
	 * 
	 * @param key
	 * @param input
	 * @param metadata
	 * @return
	 * @throws CosClientException
	 * @throws CosServiceException
	 */
	public PutObjectResult putObject(String key, InputStream input, ObjectMetadata metadata)
			throws CosClientException, CosServiceException {
		String bucketName = bucketNamePublic;
		return cosClient.putObject(bucketName, key, input, metadata);
	}

	public String putInputStreamt(String key, InputStream input) throws CosClientException, CosServiceException {
		key = imageDir + key;
		ObjectMetadata objectMetadata = new ObjectMetadata();
		// 设置输入流长度为 500
		objectMetadata.setContentLength(1024 * 10 * 10);
		// 设置 Content type, 默认是 application/octet-stream
		objectMetadata.setContentType("image/jpeg");
		PutObjectResult putObjectResult = cosClient.putObject(bucketNamePublic, key, input, objectMetadata);
		String etag = putObjectResult.getETag();
		return etag;
	}

	/**
	 * 上传图片文件
	 * 
	 * @param file
	 * @param key
	 * @return
	 */
	public String putImageObject(File file, String key) {

		String realKey = imageDir + key;
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketNamePublic, realKey, file);
		// 设置存储类型为低频
		putObjectRequest.setStorageClass(StorageClass.Standard_IA);

		// 设置自定义属性(如 content-type, content-disposition 等)
		ObjectMetadata objectMetadata = new ObjectMetadata();

		// 设置 Content type, 默认是 application/octet-stream
		objectMetadata.setContentType("image/jpeg");
		putObjectRequest.setMetadata(objectMetadata);
		PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
		putObjectResult.getETag(); // 获取文件的 etag

		return realKey;
	}


	public String putImageObject(File file) {
		String fileName = file.getName();
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		String key = getFileName("." + suffix);
		return putImageObject(file, key);
	}



	public String getFileName(String suffix) {
		// 文件路径
		return UUIDUtils.getCode() + suffix;
	}

	

	/**
	 * 拷贝文件
	 * 
	 * @param srcKey
	 *            源文件路径
	 * @param destKey
	 *            目标文件路径
	 * @return
	 */
	public boolean copyBySrcDestKey(String srcKey, String destKey) {
		// 要拷贝的bucket region, 支持跨园区拷贝
		Region srcBucketRegion = new Region("ap-chengdu");
		// 源bucket, bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
		String srcBucketName = bucketNamePublic;
		// 要拷贝的源文件
		// String srcKey = "aaa/bbb.txt";
		// 目的bucket, bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
		String destBucketName = srcBucketName;
		// 要拷贝的目的文件
		// String destKey = "ccc/ddd.txt";

		// 生成用于获取源文件信息的srcCOSClient
		CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketRegion, srcBucketName, srcKey,
				destBucketName, destKey);
		try {
			Copy copy = transferManager.copy(copyObjectRequest, cosClient, null);
			// 返回一个异步结果copy, 可同步的调用waitForCopyResult等待copy结束, 成功返回CopyResult, 失败抛出异常.
			CopyResult copyResult = copy.waitForCopyResult();
			return true;
		} catch (CosServiceException e) {
			e.printStackTrace();
		} catch (CosClientException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 删除对象
	 * 
	 * @param key
	 */
	public void deleteObject(String key) {
		cosClient.deleteObject(bucketNamePublic, key);
	}

	public static void main(String[] args) {
		String fileName = "k1.jpg";
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		System.out.println("tste ==>" + suffix);

	}

}