腾讯云存储-java接入

腾讯云存储

腾讯云存储开发文档地址:https://cloud.tencent.com/document/product/436/10199
说明:
1-对象健就是文件在存储桶中的文件全路径名。
2-欢迎有疑问的朋友留言共同学习

一:pom依赖

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

二:配置文件application.yml

server:
  port: 8080
tencent:
  cos:
    qcloudDomain: https://xxxxxx.cos.xxxxx.myqcloud.com #存储服务域名
    qcloudPrefix: xxx	#存储文件前缀
    qcloudAppId: xxx
    qcloudSecretId: xxx
    qcloudSecretKey: xxx
    qcloudBucketName: xxx	#存储桶名称
    qcloudRegion: xxx	#区域名格式为ap-xxx  eg: ap-nanjing  与存储服务域名cos后字段相同
spring:
  application:
    name: cos-server

三:在项目配置类中加入COSClient配置

3.1-CosConfig配置类

@Data
@Configuration
@ConfigurationProperties("tencent.cos")
@NoArgsConstructor
@AllArgsConstructor
public class CosConfig {
    private String qcloudDomain;
    private String qcloudPrefix;
    private String qcloudAppId;
    private String qcloudSecretId;
    private String qcloudSecretKey;
    private String qcloudBucketName;
    private String qcloudRegion;
}

3.2-CosConfiguration配置类

hint:若项目中已有配置类,在项目配置类中加入COSClient的Bean即可

@Configuration
public class CosConfiguration {
    @Autowired
    private CosConfig cosConfig;
    @Bean
    public COSClient getCosClient(){
        // 1 初始化用户身份信息(secretId, secretKey)。
        // SECRETID和SECRETKEY请登录访问管理控制台进行查看和管理
        String secretId = cosConfig.getQcloudSecretId();
        String secretKey = cosConfig.getQcloudSecretKey();
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(cosConfig.getQcloudRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }
}

四:生产环境CosService类

@Service
public class CosService {
    @Autowired
    private COSClient cosClient;
    @Autowired
    private CosConfig config;

    //上传文件
    public  String upload(byte[] data,String fileName){
        // 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
        String bucketName = config.getQcloudBucketName();
        String key = getPath(config.getQcloudPrefix(),fileName);
        ObjectMetadata metadate=new ObjectMetadata();
        metadate.setContentLength(data.length);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,new ByteArrayInputStream(data),metadate);
        // 设置文件大小大于等于10MB才使用分块上传
        TransferManagerConfiguration transferManagerConfiguration = new TransferManagerConfiguration();
        transferManagerConfiguration.setMultipartUploadThreshold(10*1024*1024);
        TransferManager transferManager=new TransferManager(cosClient);
        transferManager.setConfiguration(transferManagerConfiguration);
        //文件上传
        try{
            Upload upload = transferManager.upload(putObjectRequest);
            // 等待传输结束
            // UploadResult uploadResult = upload.waitForUploadResult();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
//        cosClient.shutdown();
        return key;
    }
    
    //上传过大文件服务
    public String upload2(InputStream inputStream, String path) {
        String bucketName = config.getQcloudBucketName();
        String key = path;
        ObjectMetadata metadata = new ObjectMetadata();
//        metadata.setContentLength(data.length);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,inputStream, metadata);
        // 设置文件大小大于等于10MB才使用分块上传
        TransferManagerConfiguration transferManagerConfiguration = new TransferManagerConfiguration();
        transferManagerConfiguration.setMultipartUploadThreshold(10*1024*1024);
        TransferManager transferManager = new TransferManager(client);
        transferManager.setConfiguration(transferManagerConfiguration);
        Upload upload = null;
        try {
            //文件上传
            upload = transferManager.upload(putObjectRequest);
        } catch (CosClientException e) {
            e.printStackTrace();
            return null;
        }
        return key;
    }


    //根据key获取临时url
    public String geturlBykey(String key){
        //设置临时url有效时长2小时
        Date date = new Date(System.currentTimeMillis() + 2 * 60 * 60 * 1000);
        URL url = cosClient.generatePresignedUrl(config.getQcloudBucketName(),key,date);
//        cosClient.shutdown();
        return url.toString();
    }

    //根据文件key下载文件
    public  String download(String key){
        String bucketName = config.getQcloudBucketName();
        //根据系统指定文件路径
        String os = System.getProperty("os.name");
        String path="";
        //判断是什么操作系统
        if(os.toLowerCase().startsWith("win")){
            path = "D:\\policTest\\";
        }else{
            path ="/mnt/upload/";
//                path ="/usr/share/nginx/html/image"+filename;
        }

        File localDownFile = new File(path);
        if(!localDownFile.exists()){
            localDownFile.mkdirs();
        }
        String suffix = key.substring(key.lastIndexOf("."), key.length());
        path+=UUID.randomUUID()+suffix;
        localDownFile=new File(path);
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        // 限流使用的单位是bit/s, 这里设置下载带宽限制为 10MB/s
        getObjectRequest.setTrafficLimit(80*1024*1024);
        // 下载文件
        TransferManager transferManager=new TransferManager(cosClient);
        Download download = transferManager.download(getObjectRequest, localDownFile);
        // 等待传输结束(如果想同步的等待上传结束,则调用 waitForCompletion)
        //download.waitForCompletion();
//        cosClient.shutdown();
        return localDownFile.getAbsolutePath();
    }

    //生成文件路径
    public static String getPath(String prex,String fileName){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String path =simpleDateFormat.format(new Date()) + "/"+ UUID.randomUUID().toString().replace("-", "");
        if(prex!=null){
            path=prex+"/"+path;
        }
        return path+"_"+fileName;
    }
}

五:生产环境CosController类

@RestController
@RequestMapping("/costest")
public class CosController {
    @Autowired
    private CosService cosService;

    //允许的文件格式
    private String fileFormat=".jpg,.jpeg,.png,.gif";

    private String allowedPackage = ".zip,.rar";
    
    //文件上传
    @PostMapping("upload")
    public String upload(@RequestParam("file")MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String suffix=filename.substring(filename.lastIndexOf("."),filename.length());
        //判断文件格式是否支持
        if(!fileFormat.contains(suffix.trim().toLowerCase())){
            return "文件格式不支持";
        }
        String upload = cosService.upload(file.getBytes(), filename);
        return upload;
    }
    
    //上传大文件接口
    @RequestMapping(value = "/package2", method = RequestMethod.POST)
    public CommonResult<String> uploadCosFile2(@RequestParam("file") MultipartFile file, HttpServletRequest request)
            throws IOException {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        if (!allowedPackage.contains(suffix.trim().toLowerCase())) {
            return CommonResult.error("文件格式不支持!");
        }
        String uri = storageService.uploadSuffix2(file.getInputStream(), fileName);
        if (StringUtils.isEmpty(uri)) {
            return CommonResult.error("上传失败");
        }
        return CommonResult.success().setData(uri);
    }

    //文件下载
    @GetMapping("download")
    public String download(@RequestParam("key")String key){
        String download = cosService.download(key);
        return download;
    }

    //根据key获取临时url
    @GetMapping("getUrlByKey")
    public String getUrlByKey(@RequestParam("key")String key){
        return cosService.geturlBykey(key);
    }

}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值