S3 对象存储,实现图片上传功能
1.maven 依赖
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.12.410</version>
</dependency>
2.S3 工具类
@Slf4j
@Component
public class S3Manager {
private static final String AWS_ACCESS_KEY = "QTR19VOU2J3HC9U2ZB8W";
private static final String AWS_SECRET_KEY = "gs2Kr2efO6ttkOyq9BPPXwThyJ4PjBy7PBQPxOJZ";
private static final String ENDPOINT = "https://ip:端口号";
private static final String DEFAULT_BUCKETNAME = "xxxxx";
private static volatile AmazonS3 amazonClient = null;
static {
S3Manager s3Manager = new S3Manager();
s3Manager.getAmazonClient();
}
private AmazonS3 getAmazonClient() {
if(amazonClient == null) {
synchronized (S3Manager.class) {
if (amazonClient == null) {
AWSCredentials credentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY);
ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setProtocol(Protocol.HTTP);
AmazonS3 conn = AmazonS3ClientBuilder.standard()
.withClientConfiguration(clientConfig)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(ENDPOINT, ""))
.withPathStyleAccessEnabled(true)
.build();
amazonClient = conn;
}
}
}
return amazonClient;
}
public static PutObjectResult uploadFile(String bucket, File file, String fileKey) {
PutObjectRequest request = new PutObjectRequest(bucket, fileKey, file);
return amazonClient.putObject(request);
}
public static PutObjectResult uploadFile(String bucketName, MultipartFile multipartFile, String fileKey) throws IOException {
return uploadFile(bucketName, multipartFile.getInputStream(), multipartFile.getSize(), multipartFile.getContentType(), fileKey);
}
public static PutObjectResult uploadFile(String bucketName, InputStream fileInput, Long contentLength, String fileContentType, String fileKey) {
PutObjectRequest request = new PutObjectRequest(bucketName, fileKey, fileInput, null);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(contentLength);
if (StrUtil.isNotBlank(fileContentType)) {
metadata.setContentType(fileContentType);
request.setMetadata(metadata);
}
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, fileKey);
urlRequest.setExpiration(null);
URL url = amazonClient.generatePresignedUrl(urlRequest);
log.info("[s3文件上传文件路径]----》url:{}",url);
return amazonClient.putObject(request);
}
public static String uploadFileGetUrl(String bucketName, MultipartFile multipartFile, String fileKey) throws IOException {
InputStream fileInput = multipartFile.getInputStream();
Long contentLength = multipartFile.getSize();
String fileContentType = multipartFile.getContentType();
PutObjectRequest request = new PutObjectRequest(bucketName, fileKey, fileInput, null).withCannedAcl(CannedAccessControlList.PublicRead);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(contentLength);
if (StrUtil.isNotBlank(fileContentType)) {
metadata.setContentType(fileContentType);
request.setMetadata(metadata);
}
PutObjectResult putObjectResult = amazonClient.putObject(request);
List<Bucket> buckets = amazonClient.listBuckets();
log.info("s3文件云平台存储桶列表,{}", buckets);
String url = ENDPOINT+"/"+bucketName+"/"+fileKey;
log.info("[s3文件上传文件路径]----》url:{}",url);
return url;
}
public static InputStream downloadFile(String bucketName, String fileKey) {
GetObjectRequest request = new GetObjectRequest(bucketName, fileKey);
S3Object response = amazonClient.getObject(request);
return response.getObjectContent();
}
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String bucketName, String fileKey) throws IOException {
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileKey);
InputStream is = downloadFile(bucketName, fileKey);
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
}
public static void checkBucket(String bucketName) {
if (amazonClient.doesBucketExist(bucketName)) {
log.warn("Storage s3 api, bucketName is found: " + bucketName);
} else {
log.warn("Storage s3 api, bucketName is not exist, create it: " + bucketName);
amazonClient.createBucket(bucketName);
}
}
public static List<Bucket> getBucketList() {
List<Bucket> buckets = amazonClient.listBuckets();
for (Bucket bucket : buckets) {
System.out.println(bucket.getName() + "\t" +
DateUtil.date(bucket.getCreationDate()));
}
return buckets;
}
public static void deleteBucket(String bucketName) {
amazonClient.deleteBucket(bucketName);
}
public static ObjectListing getObjectListing(String bucketName) {
ObjectListing objects = amazonClient.listObjects(bucketName);
do {
for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
log.info("\n文件名:" + objectSummary.getKey() + "\n" + "文件大小:" + objectSummary.getSize() + "\n" + "最后一次修改时间:" + DateUtil.date(objectSummary.getLastModified()));
}
objects = amazonClient.listNextBatchOfObjects(objects);
} while (objects.isTruncated());
return objects;
}
public static void deleteObject(String bucketName, String fileKey) {
amazonClient.deleteObject(bucketName, fileKey);
}
public static void main(String[] args) {
checkBucket(DEFAULT_BUCKETNAME);
getObjectListing(DEFAULT_BUCKETNAME);
}
}
3.具体代码实现
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
@ApiOperation("上传")
public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)throws Exception {
Result result = new Result();
S3Manager.checkBucket("yxf-bucket-01");
String oldName = file.getOriginalFilename();
String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String newName = IdWorker.get32UUID()+substring;
String url = S3Manager.uploadFileGetUrl("xxxxx", file, newName);
result.setData(url);
return result.success();
}