创建工具类CosUtil

1.引入相关参数

代码如下(示例):

	private static String appId;

    private static String secretId;

    private static String secretKey;

    private static String region;

    private static String photoBucket;
以上参数都可以在云存储中找到。 为了方便维护,相关参数值在application.yml中进行配置
tencent:
  appId: 你的在存储桶上的id
  secretId: 同上
  secretKey: 同上
  region: 同上 格式为(ap-nanjing)
  photoBucket: 你的存储桶名
将值注入类中,代码如下:
//加入这两个注解以匹配application.yml
@Component
@ConfigurationProperties(prefix = "tencent",ignoreInvalidFields = true,ignoreUnknownFields = true)
public class CosUtil {
    private static String appId;

    private static String secretId;

    private static String secretKey;

    private static String region;

    private static String photoBucket;

	//注入值
    @Value("${tencent.appId}")
    public void setAppId(String appId) {
        this.appId = appId;
    }
    @Value("${tencent.secretId}")
    public void setSecretId(String secretId) {
        this.secretId = secretId;
    }
    @Value("${tencent.secretKey}")
    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }
    @Value("${tencent.region}")
    public void setRegion(String region) {
        this.region = region;
    }
    @Value("${tencent.photoBucket}")
    public void setPhotoBucket(String photoBucket) {
        this.photoBucket = photoBucket;
    }
    .....................

2.编写实现类

代码如下(示例):

/**
     * 初始化CosClient相关配置, appid、accessKey、secretKey、region
     *
     * @return
     */
    public COSClient getCosClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    /**
     * 上传文件
     *@Param //MultipartFile:前台传入的文件 FileType:枚举类 根据值不同,实现的功能不同
     * @return //绝对路径和相对路径都OK
     */
    public String uploadFile(MultipartFile file,FileType type) throws IOException {
    	//上传至存储桶的名字
        String KEY = "/" + file.getOriginalFilename();
        String bucket = null;
        //根据业务模块,上传至其他存储桶
        if (type==FileType.INSTRUCTOR){
            bucket = photoBucket;
        }else{
            bucket = photoBucket;
        }
        //获得文件名
        String fileName = file.getOriginalFilename();
        //将图片的具体信息传入ObjectMetadate类
        ObjectMetadata meta=new ObjectMetadata();
        //必须设置该属性
        meta.setContentLength(file.getSize());
        //设置字符编码格式
        meta.setContentEncoding("UTF-8");
        //获得文件后缀名并根据传入的图片格式设置ContentType
        if (".png".equals(fileName.lastIndexOf("."))){
            meta.setContentType("image/png");
        }else if (".jpg".equals(fileName.lastIndexOf("."))){
            meta.setContentType("image/jpeg");
        }
        //SDK构造方法,具体参造[SDKAPI](https://help.aliyun.com/document_detail/32008.htm?spm=a2c4g.11186623.2.3.65ac605fhxBPgG)
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, KEY, file.getInputStream(),meta);
        putObjectRequest.setStorageClass(StorageClass.Standard);
        COSClient client = getCosClient();
        try {
            PutObjectResult putObjectResult = client.putObject(putObjectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭客户端
        client.shutdown();
        //拼接获得存储桶中可访问的地址
        return "https://"+bucket+".cos."+region+".myqcloud.com"+KEY;
    }

在Controller层可直接调用该方法获得Url实现相关功能

public R upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new TTOAException("上传文件不能为空");
		}

		//上传文件
		CosUtil client = new CosUtil();
		String url = client.uploadFile(file, FileType.TEACHER);

		return R.ok().put("url",url);
	}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐