一、介紹
Amazon S3(Simple Storage Service)是亞馬遜云計算平臺提供的一種對象存儲服務(wù),可以用于存儲和檢索任意類型的數(shù)據(jù)。在Java開發(fā)中,我們可以通過AWS SDK for Java來實(shí)現(xiàn)與Amazon S3的集成。
官方文檔
https://docs.aws.amazon.com/zh_cn/sdk-for-java/v1/developer-guide/examples-s3.html文章來源:http://www.zghlxwxcb.cn/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() {
// 創(chuàng)建連接
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();
// 桶不在則創(chuàng)建桶
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. 測試運(yùn)行結(jié)果
文章來源地址http://www.zghlxwxcb.cn/news/detail-833894.html
到了這里,關(guān)于Java AWS S3 文件上傳實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!