Aws s3 (Java 使用)

时间:2025-03-04 16:25:45

awsConfig

import ;
import ;
import ;
import ;
import ;
import .s3.AmazonS3;
import .s3.AmazonS3ClientBuilder;
import ;
import .slf4j.Slf4j;
import ;
import ;
import ;
import ;

@Slf4j
@Data
@EnableScheduling
@Configuration
public class AwsConfig {

    @Value("${}")
    private String accessKey;

    @Value("${}")
    private String secretKey;

    @Value("${}")
    private String region;

    @Value("${}")
    private String bucketName;

    @Bean
    public AmazonS3 getAmazonS3() {
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        ClientConfiguration baseOpts = new ClientConfiguration();
        //
        ("S3SignerType");
        ();
        //
        AmazonS3 amazonS3 = ()
                .withRegion(region)
                .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
//                .withEndpointConfiguration(new (hostName, region))  // 如果有endpoint,可以用这个,这个和withRegion(Region)不能一起使用
//                .withPathStyleAccessEnabled(true)  // 如果配置了S3域名,就需要加这个进行路径访问,要不然会报AccessKey不存在的问题
                .withClientConfiguration(baseOpts)
                .build();
        return amazonS3;
    }
}

Biz层(也就是service层)

import .s3.AmazonS3;
import ..*;
import ;
import ;
import ;
import ;
import ;
import ;
import .slf4j.Slf4j;
import .;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;

@Slf4j
@Service
public class AwsS3Biz {


    @Value("${}")
    private String bucketName;


    @Autowired
    private AwsConfig s3;

    @Autowired
    private VocAnalyzingService vocAnalyzingService;


    public String up(MultipartFile multipartFile){
        ObjectMetadata objectMetadata = new ObjectMetadata();
        (());
        (());

        //  桶名,文件夹名,本地文件路径
        String key = ();
        try {
            s3.getAmazonS3().putObject(new PutObjectRequest(bucketName, key, (), objectMetadata));
        } catch (IOException e) {
            ();
        }
        return key;
    }


    public String upload(MultipartFile multipartFile,Long analyzingId) {
        if (()) {
            throw new BusinessException(408,"文件为空!");
        }
        // 上传之前判断是否存在报表 getAwsKey //TODO getAwsKey
        VocAnalyzing analyzing = new VocAnalyzing();
        (analyzingId);
        (().getAccountId());
//        if (!((analyzingId).getAwsKey())){
//            throw new BusinessException(406,"Manual report already exists.");
//        }
        //
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            (());
            (());
            // 文件后缀
//            String suffix = ().substring(().lastIndexOf("."));
            String key = ().toString();
            PutObjectResult putObjectResult = s3.getAmazonS3()
                    .putObject(new PutObjectRequest(bucketName, key, (), objectMetadata));
            // 上传成功 关联到voc分析
            if (null != putObjectResult) {
                // 设置aws对象的 key
//                (key); //TODO
//                (analyzing);
                // 返回key
                return key;
            }
        } catch (Exception e) {
            ("Upload files to the bucket,Failed:{}", ());
            ();
        }
        return null;
    }


    public String downloadFile(String key) {
        try {
            if ((key)) {
                return null;
            }
            GeneratePresignedUrlRequest httpRequest = new GeneratePresignedUrlRequest(bucketName, key);
//            //设置过期时间
//            (expirationDate);
            return s3.getAmazonS3().generatePresignedUrl(httpRequest).toString();
        } catch (Exception e) {
            ();
        }
        return null;
    }


    /**
     * 判断名为bucketName的bucket里面是否有一个名为key的object
     * @param bucketName
     * @param key
     * @return
     */
    public boolean isObjectExit(String bucketName, String key) {
        int len = ();
        ObjectListing objectListing = s3.getAmazonS3().listObjects(bucketName);
        String s = new String();
        for(S3ObjectSummary objectSummary : ()) {
            s = ();
            int slen = ();
            if(len == slen) {
                int i;
                for(i=0;i<len;i++) {
                    if((i) != (i)) {
                        break;
                    }
                }
                if(i == len) {
                    return true;
                }
            }
        }
        return false;
    }

    public void getAllBucketObject(){
        ObjectListing objects = s3.getAmazonS3().listObjects(bucketName);
        do {
            for (S3ObjectSummary objectSummary : ()) {
                ("Object: " + ());
            }
            objects = s3.getAmazonS3().listNextBatchOfObjects(objects);
        } while (());
    }


}

controller层

import ;
import .AwsS3Biz;

import ;
import ;
import ;
import ;
import ;
import .*;
import ;

import ;

/**
 * Web控制层:
 * @author liaoguang
 * @date 2022-03-14
 */
@RestController
@RequestMapping(value = "/vocReport")
@Validated
@SuppressWarnings("unchecked")
@Api(value = "人工报告接口", tags = { "人工报告接口" })
public class VocReportController {

    @Autowired
    private AwsS3Biz awsS3Biz;

    /**
     * 导入人工报告
     * @param file
     * @param analyzingId
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "导入人工报告",notes = "导入人工报告")
    @ApiOperationSupport(order=0)
    @PostMapping("/importReport")
    public JsonResult<Boolean> importItems(@RequestParam("file") MultipartFile file, @RequestParam("analyzingId") Long analyzingId) throws IOException {

        String key = (file,analyzingId);

        return ().data(key).build();
    }

    /**
     * 查看人工报告
     * @param
     * @return
     */
    @ApiOperation(value = "根据key查看人工报告",notes = "根据key查看人工报告")
    @ApiOperationSupport(order=1)
    @GetMapping("/{key}")
    public JsonResult<String> byAnalyzingId(@PathVariable("key") String key) {

        String url = (key);
        return ().data(url).build();
    }

    @GetMapping("/test")
    public JsonResult<String> test() {

        ();
        return ().data("ok").build();
    }
}

yml文件

aws:
  region: x
  accessKey: x
  secretKey: xxxx
  bucketName: xxx

pom依赖

<dependency>
     <groupId></groupId>
     <artifactId>aws-java-sdk-s3</artifactId>
     <version>1.11.821</version>
</dependency>