对象存储

1.从腾讯云上获取需要的资料

1. API密钥secretId和API密钥secretKey

在这里插入图片描述

2. 存储桶空间名称、存储桶所属地域、存储桶访问域名

在这里插入图片描述

2.导入依赖

我采用的是5.6.42的版本

        <!-- https://mvnrepository.com/artifact/com.qcloud/cos_api -->
        <dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.6.42</version>
        </dependency>

3.创建工具类

后期完善其他接口

package com.ddz.project.common.utils;

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.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * @program: dashen-api
 * @description 腾讯云对象存储工具类
 * @author: ddz
 * @create: 2021-04-15 16:15
 **/
@Slf4j
@Component
public class QCloudCosUtils {
    //API密钥secretId
    private String secretId="API密钥secretId";
    
    //API密钥secretKey
    private String secretKey="API密钥secretKey";
    
    //存储桶所属地域
    private String region="存储桶所属地域";
    
    //存储桶空间名称
    private String bucketName="存储桶空间名称";
    
    //存储桶访问域名
    private String url;
    
    //上传文件前缀路径(eg:/images/) 设置自己的主目录
    private String prefix;

    /**
     * 上传File类型的文件
     *
     * @param file 文件
     * @return 上传文件在存储桶的链接
     */
    public String upload(File file) {
        //生成唯一文件名
        String newFileName = generateUniqueName(file.getName());
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DATE);
        //文件在存储桶中的key
        String key = prefix + year + "/" + month + "/" + day + "/" + newFileName;
        //声明客户端
        COSClient cosClient = null;
        try {
            //初始化用户身份信息(secretId,secretKey)
            COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
            //设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            //生成cos客户端
            cosClient = new COSClient(cosCredentials, clientConfig);
            //创建存储对象的请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            //执行上传并返回结果信息
//            new PutObjectRequest(bucketName)
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return url + key;
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端(关闭后台线程)
            cosClient.shutdown();
        }
        return null;
    }

    /**
     * upload()重载方法
     *
     * @param multipartFile 文件对象
     * @return 上传文件在存储桶的链接
     */
    public String upload(MultipartFile multipartFile) {
        //生成唯一文件名
        String newFileName = generateUniqueName(multipartFile.getOriginalFilename());
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DATE);
        //文件在存储桶中的key
        String key = prefix + year + "/" + month + "/" + day + "/" + newFileName;
        //声明客户端
        COSClient cosClient = null;
        //准备将MultipartFile类型转为File类型
        File file = null;
        try {
            //生成临时文件
            file = File.createTempFile("temp", null);
            //将MultipartFile类型转为File类型
            multipartFile.transferTo(file);
            //初始化用户身份信息(secretId,secretKey)
            COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
            //设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            //生成cos客户端
            cosClient = new COSClient(cosCredentials, clientConfig);
            //创建存储对象的请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            //执行上传并返回结果信息
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return url + key;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端(关闭后台线程)
            cosClient.shutdown();
        }
        return null;
    }

/**
     * upload()重载方法
     * 流方式上传
     *
     * @param multipartFile
     * @return 上传文件在存储桶的链接
     */
    public String uploadStream(MultipartFile multipartFile) {
        //生成唯一文件名
        String newFileName = generateUniqueName(multipartFile.getOriginalFilename());
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DATE);
        //文件在存储桶中的key
        String key = prefix + year + "/" + month + "/" + day + "/" + newFileName;
        //声明客户端
        COSClient cosClient = null;
        try {
            //初始化用户身份信息(secretId,secretKey)
            COSCredentials cosCredentials = new BasicCOSCredentials(secretId, secretKey);
            //设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            //生成cos客户端
            cosClient = new COSClient(cosCredentials, clientConfig);
            // 获取文件流
            InputStream inputStream = multipartFile.getInputStream();
            // 获取文件名
            String fileName = multipartFile.getOriginalFilename();
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //创建存储对象的请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
            //执行上传并返回结果信息
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return url + key;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端(关闭后台线程)
            cosClient.shutdown();
        }
        return null;
    }

/**
     * Description: 判断Cos服务文件上传时文件的contentType
     *
     * @param filenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
                || filenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 根据UUID生成唯一文件名
     *
     * @param originalName
     * @return
     */
    public String generateUniqueName(String originalName) {
        return SnowflakeUtils.nextIdStr() + originalName.substring(originalName.lastIndexOf("."));
    }
}

短信

1.登录腾讯云获取资料

1. API密钥secretId和API密钥secretKey

在这里插入图片描述

2. AppId、模板IDTemplateId

appId在应用列表里面
在这里插入图片描述

先创建签名,再用签名创建模板、注意模板需要的参数有几个
在这里插入图片描述
在这里插入图片描述

2. 导入依赖

        <!-- https://mvnrepository.com/artifact/com.tencentcloudapi/tencentcloud-sdk-java -->
        <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-sdk-java</artifactId>
            <version>4.0.11</version>
        </dependency>

3. 创建工具类

package com.communist.common.util;

import com.communist.common.constant.SmsConstant;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import org.springframework.stereotype.Component;

/**
 * @Author ddz
 * @ClassName SmsUtils
 * @Description 短信
 * @Date 2021/8/2 11:09
 * @Version 1.0
 **/
@Component
public class SmsUtils {
    //API密钥secretId
    private String secretId="API密钥secretId";
    
    //API密钥secretKey
    private String secretKey="API密钥secretKey";

    // appId
    private String appId = "appId";

    // 短信模板id
    private String templateId = "短信模板id";

    /**
     * 发送短信
     *
     * @param phone  手机号
     * @param params 模板参数,若无模板参数,则设置为空。  [前缀,验证码,时间]
     * @return
     */
    public boolean sendSms(String phone, String[] params) throws TencentCloudSDKException {
        // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
        // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
        Credential cred = new Credential(secretId, secretKey);
        // 实例化一个http选项,可选的,没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        // 实例化一个client选项,可选的,没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

        // 实例化一个请求对象,每个接口都会对应一个request对象
        SendSmsRequest req = new SendSmsRequest();
        // +86 代表国内
        phone = "+86" + phone;
        String[] phoneNumberSet = {phone};
        req.setPhoneNumberSet(phoneNumberSet);
        req.setSmsSdkAppid(appId);
        req.setTemplateID(templateId);
        req.setTemplateParamSet(params);
        // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
        SendSmsResponse resp = client.SendSms(req);
        // 输出json格式的字符串回包
        SendStatus[] sendStatusSet = resp.getSendStatusSet();
        SendStatus result = sendStatusSet[0];
        if (null != result) {
            String code = result.getCode();
            if ("Ok".equals(code)) {
                return true;
            }
        }
        return false;
    }
}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐