COS对象存储服务的使用

---------------------------------------------------------------------------------------------
[版权申明:本文系做者原创,转载请注明出处] 
文章出处: http://blog.csdn.net/sdksdk0/article/details/53639792
做者:朱培      ID:sdksdk0     

--------------------------------------------------------------------------------------------html

在不少图片上传以及文件上传下载操做的时候,我以前一直使用的是nginx在服务器中划分出一个静态的文件服务器,我主要用于存放图片。而后由于某种缘由,而后我换成了COS。java

官网的简介是这样的:nginx

对象存储服务(Cloud Object Service)是面向企业和我的开发者提供的高可用,高稳定,强安全的云端存储服务。您能够将任意数量和形式的非结构化数据放入COS,并在其中实现数据的管理和处理。COS支持标准的Restful API接口,您能够快速上手使用,按实际使用量计费,无最低使用限制。git


而后我最开始是抱着死马当活马医的心态来使用的,进度上面要求我是要尽快完成的,并且我发现对于我这种小网站来讲使用这个COS服务基本上是免费的,简直就是捡到宝的感受,哈哈!因此我就赶忙放弃了个人nginx图片服务器。而后去github上面下载他们的官方文档。github

https://github.com/tencentyun/cos-java-sdk-v4
apache

在在里面有个demo.java,而后直接拿过来用就好了。由于我项目上传的图片是要按年月日自动生成目录来存放的,因此官方提供的那段代码是很是不够用的。json

maven坐标是:api

<dependency>
				<groupId>com.qcloud</groupId>
				<artifactId>cos_api</artifactId>
				<version>4.2</version>
			</dependency>

通常在真实项目中只导入这个是不行的,还须要加入http的jar包,因此还须要:并且这个版本还要匹配,不然在本地localhost的时候是能够用的,可是一道服务器上就会说你少jar包了。

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.3.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.1</version>
		</dependency>

资源初始化:


// 设置用户属性, 包括appid, secretId和SecretKey
        // 这些属性能够经过cos控制台获取(https://console.qcloud.com/cos)
        long appId = 1000000;
        String secretId = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
        String secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
        // 设置要操做的bucket
        String bucketName = "xxxxxxxxx";
        // 初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        // 设置bucket所在的区域,好比广州(gz), 天津(tj)
        clientConfig.setRegion("gz");
        // 初始化秘钥信息
        Credentials cred = new Credentials(appId, secretId, secretKey);
        // 初始化cosClient
        COSClient cosClient = new COSClient(clientConfig, cred);


我只使用了其中的文件上传功能:安全


// 1. 上传文件(默认不覆盖)
        // 将本地的local_file_1.txt上传到bucket下的根分区下,并命名为sample_file.txt
        // 默认不覆盖, 若是cos上已有文件, 则返回错误
        String cosFilePath = "/sample_file.txt";
        String localFilePath1 = "src/test/resources/bigfile.txt";
        UploadFileRequest uploadFileRequest =
                new UploadFileRequest(bucketName, cosFilePath, localFilePath1);
        uploadFileRequest.setEnableSavePoint(false);
        uploadFileRequest.setEnableShaDigest(false);
        String uploadFileRet = cosClient.uploadFile(uploadFileRequest);
        System.out.println("upload file ret:" + uploadFileRet);

这段代码只是一个入门程序,因此在咱们实际应用中确定是须要进行修改的。例如我图片上传的吧,进来的是一个二进制流文件,总不能用String来接收吧,因此我将其改变了一下:

我传进去的是一个MultipartFile。因此接收我须要一个byte[].很是方便就改好了。服务器

MultipartFile uploadFile

 // 1. 上传文件(默认不覆盖)
	        // 将本地的local_file_1.txt上传到bucket下的根分区下,并命名为sample_file.txt
	        // 默认不覆盖, 若是cos上已有文件, 则返回错误
	        String cosFilePath = "/images"+imagePath+"/"+newName;
	        byte[] localFilePath1 = uploadFile.getBytes();
	        UploadFileRequest uploadFileRequest =
	                new UploadFileRequest(bucketName, cosFilePath, localFilePath1);
	        uploadFileRequest.setEnableSavePoint(false);
	        uploadFileRequest.setEnableShaDigest(false);
	        String uploadFileRet = cosClient.uploadFile(uploadFileRequest);

那么我须要按年月日来生成目录,因此我须要这样。

// 生成一个新的文件
			// 取原始文件名
			String oldName = uploadFile.getOriginalFilename();
			// 生成新文件名
//		UUID.randomUUID();
			String newName = IDUtils.genImageName();
			newName = newName + oldName.substring(oldName.lastIndexOf("."));
			// 图片上传
			String imagePath = new DateTime().toString("/yyyy/MM/dd");

因此完整代码就以下了:


@Override
	public Map uploadPicture(MultipartFile uploadFile) {
		Map resultMap = new HashMap();
		
		try {
			// 生成一个新的文件
			// 取原始文件名
			String oldName = uploadFile.getOriginalFilename();
			// 生成新文件名
//		UUID.randomUUID();
			String newName = IDUtils.genImageName();
			newName = newName + oldName.substring(oldName.lastIndexOf("."));
			// 图片上传
			String imagePath = new DateTime().toString("/yyyy/MM/dd");

			  // 设置用户属性, 包括appid, secretId和SecretKey
	        // 这些属性能够经过cos控制台获取(https://console.qcloud.com/cos)
	       long appId = 1000000;
        String secretId = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
        String secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
        // 设置要操做的bucket
        String bucketName = "xxxxxxxxx";
	        // 初始化客户端配置
	        ClientConfig clientConfig = new ClientConfig();
	        // 设置bucket所在的区域,好比广州(gz), 天津(tj)
	        clientConfig.setRegion("gz");
	        // 初始化秘钥信息
	        Credentials cred = new Credentials(appId, secretId, secretKey);
	        // 初始化cosClient
	        COSClient cosClient = new COSClient(clientConfig, cred);
	        ///////////////////////////////////////////////////////////////
	        // 文件操做 //
	        ///////////////////////////////////////////////////////////////
	        // 1. 上传文件(默认不覆盖)
	        // 将本地的local_file_1.txt上传到bucket下的根分区下,并命名为sample_file.txt
	        // 默认不覆盖, 若是cos上已有文件, 则返回错误
	        String cosFilePath = "/images"+imagePath+"/"+newName;
	        byte[] localFilePath1 = uploadFile.getBytes();
	        UploadFileRequest uploadFileRequest =
	                new UploadFileRequest(bucketName, cosFilePath, localFilePath1);
	        uploadFileRequest.setEnableSavePoint(false);
	        uploadFileRequest.setEnableShaDigest(false);
	        String uploadFileRet = cosClient.uploadFile(uploadFileRequest);
			
	        //System.out.println("upload file ret:" + uploadFileRet);
			
			
	        String json=JsonUtils.objectToJson(uploadFileRet);
			//System.out.println(json.toString());
			
			
			resultMap.put("error", 0);
			resultMap.put("url", IMAGE_BASE_URL +"/images"+imagePath+"/"+newName);
			
			
			return resultMap;
		} catch (Exception e) {
			resultMap.put("error", 1);
			resultMap.put("message", "文件上传发生异常");
			return resultMap;
		}
	}

这个IMAGE_BASE_URL就是这个对象存储的位置。例如你随便上传一个文件的时候,都会给你一个文件的地址的前缀部分。




完成以后能够在控制台查看,或者网址访问,若是须要图片的时候,就把这个url拿出用便可,例如我就是放在img标签的src里就能够直接使用了。




前面的工具类IDUtils.java


public class IDUtils {

	/**
	 * 图片名生成
	 */
	public static String genImageName() {
		//取当前时间的长整形值包含毫秒
		long millis = System.currentTimeMillis();
		//long millis = System.nanoTime();
		//加上三位随机数
		Random random = new Random();
		int end3 = random.nextInt(999);
		//若是不足三位前面补0
		String str = millis + String.format("%03d", end3);
		
		return str;
	}
}






总结:使用对象存储服务是一种很是高效便捷的方式,并且使用起来仍是挺简单的。点个赞。