@Configuration
@IntegrationComponentScan
@Slf4j
public class AwsPublicConfig {
@Value("${aws.s3.accessKey}")
private String accessKey;
@Value("${aws.s3.secretKey}")
private String secretKey;
@Value("${aws.s3.endPoint}")
private String endpoint;
@Value("${aws.s3.bucketName}")
private String bucketName;
@Value("${aws.s3.publicUrl}")
private String publicUrl;
@Bean
public AwsS3Utils creatMinioClient() {
return new AwsS3Utils(endpoint, bucketName, accessKey, secretKey,publicUrl);
}
}
public class AwsS3Utils {
private static AmazonS3 amazonS3;
private static String endpoint;
private static String bucketName;
private static String accessKey;
private static String secretKey;
private static String publicUrl;
private static final String SEPARATOR = "/";
private AwsS3Utils() {
}
public AwsS3Utils(String endpoint, String bucketName, String accessKey, String secretKey, String publicUrl) {
AwsS3Utils.endpoint = endpoint;
AwsS3Utils.bucketName = bucketName;
AwsS3Utils.accessKey = accessKey;
AwsS3Utils.secretKey = secretKey;
AwsS3Utils.publicUrl = publicUrl;
createAwsS3Client();
}
/**
* 创建连接
*/
private void createAwsS3Client() {
try {
if (null == amazonS3) {
log.info("amazonS3 create start");
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
amazonS3 = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withRegion(endpoint)
.build();
log.info("amazonS3 create end");
}
} catch (Exception e) {
log.error("连接amazonS3服务器异常:{}", e);
}
}
/**
* 文件上传
*
* @param file
* @return
*/
public static String uploadFile(MultipartFile file) {
StopWatch sw = new StopWatch();
sw.start();
String fileName = file.getOriginalFilename();
//获取当前时间的年月日时
String currentTime = DateUtil.today();
String path = SEPARATOR + "vip" + SEPARATOR + currentTime + SEPARATOR + fileName;
try {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
objectMetadata.setContentType(file.getContentType());
objectMetadata.setContentEncoding(StandardCharsets.UTF_8.name());
// amazonS3.putObject(bucketName, path, new ByteArrayInputStream(file.getBytes()), objectMetadata);
amazonS3.putObject(bucketName, path, new ByteArrayInputStream(file.getBytes()),objectMetadata);
sw.stop();
} catch (Exception e) {
log.info("AWS上传文件失败, 文件名:{}, 异常原因:{}", file.getOriginalFilename(), e);
throw new BusinessException("文件名有误,originalFilename:" + file.getOriginalFilename());
}
log.info("AWS uploadFile返回值:path:{}", path);
log.info(sw.prettyPrint());
return publicUrl + path;
}
}
aws s3对象存储
于 2023-02-20 22:25:03 首次发布