当前位置:   article > 正文

AWS S3 for java 文件上传_java上传图片到s3桶

java上传图片到s3桶

AWS S3 文件上传


public static String uploadFile(MultipartFile multipartFile, String time, String uuId) throws Exception {
        String aws_access_key = PropertiesUtil.getStringVal("aws_access_key");//aws_access_key
        String aws_secret_key = PropertiesUtil.getStringVal("aws_secret_key");//aws_secret_key
        String bucketName = PropertiesUtil.getStringVal("bucketName");//桶
        BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(aws_access_key, aws_secret_key);
        AWSStaticCredentialsProvider awss = new AWSStaticCredentialsProvider(basicAWSCredentials);

        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withRegion(Regions.AP_SOUTHEAST_2)
                .withCredentials(awss)
                .build();

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(multipartFile.getContentType());
        metadata.setContentLength(multipartFile.getSize());
        String urlString = null;
        try {
            StringBuffer sb = new StringBuffer(bucketName);
            sb.append("/");
            sb.append(time);
            sb.append("/");
            sb.append(uuId);
            //sb作为该文件的唯一标识符key
            s3Client.putObject(new PutObjectRequest(bucketName, sb.toString(), multipartFile.getInputStream(), metadata)
                    .withCannedAcl(CannedAccessControlList.PublicRead));//权限
            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(
                    bucketName, sb.toString());
            URL url = s3Client.generatePresignedUrl(urlRequest);
            String[] urlArr = url.toString().split("\\?");
            urlString = urlArr[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return urlString;
    }


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/285877
推荐阅读
相关标签
  

闽ICP备14008679号