实现标准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测试通过

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)