AWS S3 for java 文件上传

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;
    }


你可能感兴趣的:(aws)