微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

实现标准S3协议的附件上传

S3是Simple Storage Service的缩写,即简单存储服务。亚马逊的名词缩写也都遵循这个习惯,例如Elastic Compute Cloud缩写为EC2等等。

目前腾讯云很多对象存储组件都是兼容s3协议的,因此我们实现标准的s3协议存储调用即可在各类对象存储场景中使用,show me the code

初始化s3 认证

 AmazonS3 initAmazonS3Object() {
        // 新建一个凭证
        AWSCredentials credentials = new BasicAWSCredentials(("ak","sk");
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.withProtocol(Protocol.HTTPS);
        AmazonS3 amazonS3Client = new AmazonS3Client(credentials, clientConfig);
        // 对象网关地址
        amazonS3Client.setEndpoint(properties.getEndpoint());
        return amazonS3Client;
    }

上传的具体方法

 StoreEntity uploadFile(multipartfile file) throws UniStorageException {
        Assert.notNull(file, UniStorageProperties.ParaM_MUST_NOT_EMPTY);
        String originalName = file.getoriginalFilename();
        assert originalName != null;
        String fileType = originalName.substring(originalName.lastIndexOf(".") + 1);
        String storageName = IdGen.uuid() + "." + fileType;
        //路径修改
        String filePath = UniStorageUtils.timePathYMD(System.currentTimeMillis()) + "/" + storageName;


        System.setProperty("com.amazonaws.sdk.disableCertChecking", "true");

        AmazonS3 amazonS3 = initAmazonS3Object();
        try {

            //文件名:filePath, 文件流:file.getInputStream()
            amazonS3.putObject(properties.getBucketName(), filePath, file.getInputStream(), new ObjectMetadata());
            //文件名:filePath,CannedAccessControlList.Private:私有
            amazonS3.setobjectAcl(properties.getBucketName(), filePath, CannedAccessControlList.Private);
        } catch (Exception e) {
            log.error("存储异常{}", e);
            throw new Exception("存储异常");
        }
        return new StoreEntity(storageName, originalName, filePath, file.getSize(), fileType);
    }

以上代码在ceph、minio测试通过

原文地址:https://cloud.tencent.com/developer/article/1894964

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐