-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathS3UploadAdapter.java
More file actions
70 lines (57 loc) · 2.65 KB
/
S3UploadAdapter.java
File metadata and controls
70 lines (57 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package clap.server.adapter.outbound.infrastructure.s3;
import clap.server.application.port.outbound.s3.S3UploadPort;
import clap.server.common.annotation.architecture.InfrastructureAdapter;
import clap.server.config.s3.KakaoS3Config;
import clap.server.domain.policy.attachment.FilePathPolicyConstants;
import clap.server.exception.S3Exception;
import clap.server.exception.code.FileErrorcode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
@Slf4j
@InfrastructureAdapter
@RequiredArgsConstructor
public class S3UploadAdapter implements S3UploadPort {
private final KakaoS3Config kakaoS3Config;
private final S3Client s3Client;
public List<String> uploadFiles(final FilePathPolicyConstants filePrefix,final List<MultipartFile> multipartFiles) {
return multipartFiles.stream().map((file) -> uploadSingleFile(filePrefix, file)).toList();
}
public String uploadSingleFile(final FilePathPolicyConstants filePrefix,final MultipartFile file) {
try {
Path filePath = getFilePath(file);
String objectKey = createObjectKey(filePrefix.getPath(), file.getOriginalFilename());
uploadToS3(objectKey, filePath);
Files.delete(filePath);
return getFileUrl(objectKey);
} catch (IOException e) {
throw new S3Exception(FileErrorcode.FILE_UPLOAD_REQUEST_FAILED);
}
}
private String getFileUrl(final String objectKey) {
return kakaoS3Config.getEndpoint() + "/v1/" + kakaoS3Config.getProjectId() + '/' + kakaoS3Config.getBucketName() + '/' + objectKey;
}
private static Path getFilePath(final MultipartFile file) throws IOException {
Path path = Files.createTempFile(null,null);
Files.copy(file.getInputStream(),path, StandardCopyOption.REPLACE_EXISTING);
return path;
}
private void uploadToS3(final String filePath,final Path path) {
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(kakaoS3Config.getBucketName())
.key(filePath)
.build();
s3Client.putObject(putObjectRequest, path);
}
private String createObjectKey(final String filepath,final String fileName) {
String fileId = FileIDGenerator.createFileId();
return String.format("%s/%s-%s", filepath, fileId, fileName);
}
}