一、介绍
Amazon S3(Simple Storage Service)是亚马逊云计算平台提供的一种对象存储服务,可以用于存储和检索任意类型的数据。在Java开发中,我们可以通过AWS SDK for Java来实现与Amazon S3的集成。
官方文档
https://docs.aws.amazon.com/zh_cn/sdk-for-java/v1/developer-guide/examples-s3.html文章来源:https://www.toymoban.com/news/detail-833894.html
二、使用
1. 配置maven依赖
<!--amazon s3-->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.821</version>
</dependency>
2. 配置yaml文件
aws:
endpoint: your-endpoint
accessKey: your-accesskey
secretKey: your-secretkey
bucketName: your-bucketname
3. 注入Bean
@Configuration
public class AwsS3Config {
@Value("${aws.accessKey}")
private String accessKey;
@Value("${aws.secretKey}")
private String secretKey;
@Value("${aws.endpoint}")
private String endpoint;
@Value("${aws.bucketName}")
private String bucketName;
@Bean
public AmazonS3 getAmazonS3() {
// 创建连接
ClientConfiguration config = new ClientConfiguration();
AwsClientBuilder.EndpointConfiguration endpointConfig =
new AwsClientBuilder.EndpointConfiguration(endpoint, Regions.CN_NORTH_1.getName());
AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
AmazonS3 s3 = AmazonS3Client.builder()
.withEndpointConfiguration(endpointConfig)
.withClientConfiguration(config)
.withCredentials(awsCredentialsProvider)
.disableChunkedEncoding()
.withPathStyleAccessEnabled(true)
.build();
return s3;
}
}
4. 编写service层
@Slf4j
@Service
public class AwsS3Service {
@Value("${aws.bucketName}")
private String bucketName;
@Autowired
private AmazonS3 amazonS3;
public String upload(MultipartFile multipartFile) {
if (multipartFile.isEmpty()) {
throw new RuntimeException("文件为空!");
}
try {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(multipartFile.getContentType());
objectMetadata.setContentLength(multipartFile.getSize());
// 文件后缀
// String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
String key = UUID.randomUUID().toString();
// 桶不在则创建桶
if (!amazonS3.doesBucketExistV2(bucketName)) {
amazonS3.createBucket(bucketName);
}
PutObjectResult putObjectResult = amazonS3.putObject(new PutObjectRequest(bucketName, key, multipartFile.getInputStream(), objectMetadata));
// 上传成功
if (null != putObjectResult) {
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key);
URL url = amazonS3.generatePresignedUrl(urlRequest);
// 返回url
return url.toString();
}
} catch (Exception e) {
log.error("Upload files to the bucket,Failed:{}", e.getMessage());
e.printStackTrace();
}
return null;
}
}
5. 编写controller层
@RestController
@RequestMapping("file")
@Api(tags = "文件上传")
public class FileController {
@Autowired
private AwsS3Service awsS3Service;
@PostMapping("upload")
@ApiOperation("文件上传接口")
public APIResponse<String> abilityPictureUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
String url = awsS3Service.upload(file);
if (StringUtils.isNotEmpty(url)) {
return APIResponse.success(url);
}
return APIResponse.fail("文件上传失败");
}
}
6. 测试运行结果
文章来源地址https://www.toymoban.com/news/detail-833894.html
到了这里,关于Java AWS S3 文件上传实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!