COS對象存儲服務的使用

---------------------------------------------------------------------------------------------
[版權申明:本文系作者原創,轉載請註明出處] 
文章出處:http://blog.csdn.net/sdksdk0/article/details/53639792
作者:朱培      ID:sdksdk0     

--------------------------------------------------------------------------------------------

在很多圖片上傳以及文件上傳下載操作的時候,我之前一直使用的是nginx在服務器中劃分出一個靜態的文件服務器,我主要用於存放圖片。然後因爲某種原因,然後我換成了COS。

官網的簡介是這樣的:

對象存儲服務(Cloud Object Service)是面向企業和個人開發者提供的高可用,高穩定,強安全的雲端存儲服務。您可以將任意數量和形式的非結構化數據放入COS,並在其中實現數據的管理和處理。COS支持標準的Restful API接口,您可以快速上手使用,按實際使用量計費,無最低使用限制。


然後我最開始是抱着死馬當活馬醫的心態來使用的,進度上面要求我是要儘快完成的,而且我發現對於我這種小網站來說使用這個COS服務基本上是免費的,簡直就是撿到寶的感覺,哈哈!所以我就趕緊放棄了我的nginx圖片服務器。然後去github上面下載他們的官方文檔。

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

在在裏面有個demo.java,然後直接拿過來用就行了。因爲我項目上傳的圖片是要按年月日自動生成目錄來存放的,所以官方提供的那段代碼是非常不夠用的。

maven座標是:

<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;
	}
}






總結:使用對象存儲服務是一種非常高效便捷的方式,而且使用起來還是挺簡單的。點個贊。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章