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






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



  • 相关阅读:
    【BZOJ5137】Standing Out from the Herd(后缀自动机)
    【BZOJ1564】【NOI2009】二叉查找树(动态规划)
    仙人掌&圆方树学习笔记
    【CF487E】Tourists(圆方树)
    【BZOJ2125】最短路(仙人掌,圆方树)
    【BZOJ4818】序列计数(动态规划,生成函数)
    【BZOJ1023】仙人掌图(仙人掌,动态规划)
    【BZOJ4316】小C的独立集(仙人掌,动态规划)
    【BZOJ4316】小C的独立集(动态规划)
    【BZOJ3240】【NOI2013】矩阵游戏(数论)
  • 原文地址:https://www.cnblogs.com/xiaowangba/p/6314800.html
Copyright © 2020-2023  润新知