Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: 사진 업로드 메타데이터 지정 및 파일 처리 코드 개선 #96

Merged
merged 7 commits into from
Aug 16, 2024
86 changes: 45 additions & 41 deletions src/main/java/org/cotato/csquiz/common/S3/S3Uploader.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package org.cotato.csquiz.common.S3;

import static org.cotato.csquiz.common.util.FileUtil.checkAllowedImageFileExtension;
import static org.cotato.csquiz.common.util.FileUtil.extractFileExtension;
import static org.cotato.csquiz.common.util.FileUtil.isImageFileExtension;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.cotato.csquiz.common.entity.S3Info;
import org.cotato.csquiz.common.error.ErrorCode;
Expand All @@ -20,22 +21,21 @@
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Component
public class S3Uploader {

private static final String CONTENT_TYPE = "multipart/formed-data";
private final AmazonS3Client amazonS3;

@Value("${cloud.aws.s3.bucket}")
private String bucket;

public S3Info uploadFiles(MultipartFile multipartFile, String folderName) throws ImageException {
log.info("upload Files {}", multipartFile);
File uploadFile = convert(multipartFile)
.orElseThrow(() -> new ImageException(ErrorCode.IMAGE_PROCESSING_FAIL));
log.info("{} 사진 업로드", multipartFile.getOriginalFilename());
File uploadFile = convert(multipartFile);
String uploadUrl = upload(uploadFile, folderName);

return S3Info.builder()
Expand All @@ -48,57 +48,61 @@ public S3Info uploadFiles(MultipartFile multipartFile, String folderName) throws
public void deleteFile(S3Info s3Info) {
String fileName = s3Info.getFolderName() + "/" + s3Info.getFileName();

log.info("deleteFile fileName = {}", fileName);
try {
amazonS3.deleteObject(bucket, fileName);
} catch (SdkClientException e) {
log.error("Failed to delete file: {}", s3Info.getUrl(), e);
}
log.info("{} 사진 삭제", fileName);
amazonS3.deleteObject(bucket, fileName);
}

private String upload(File uploadFile, String dirName) {
String fileName = dirName + "/" + uploadFile.getName();
String uploadUrl = putS3(uploadFile, fileName);
removeNewFile(uploadFile);
log.info(uploadUrl);
private String upload(File localUploadFile, String dirName) throws ImageException {
String fileName = dirName + "/" + localUploadFile.getName();
String uploadUrl = putS3(localUploadFile, fileName);
Youthhing marked this conversation as resolved.
Show resolved Hide resolved
localUploadFile.delete();
return uploadUrl;
}

private void removeNewFile(File targetFile) {
if (targetFile.delete()) {
log.info("삭제 완료");
} else {
log.error("삭제 에러");

private String putS3(File uploadFile, String fileName) throws ImageException {
try {
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, uploadFile)
.withCannedAcl(CannedAccessControlList.PublicRead);

if (isImageFile(uploadFile)) {
putObjectRequest = addMetadataToRequest(putObjectRequest);
}
Youthhing marked this conversation as resolved.
Show resolved Hide resolved

amazonS3.putObject(putObjectRequest);

return amazonS3.getUrl(bucket, fileName).toString();
} catch (AmazonS3Exception e) {
throw new ImageException(ErrorCode.FILE_EXTENSION_FAULT);
Youthhing marked this conversation as resolved.
Show resolved Hide resolved
}
}

private String putS3(File uploadFile, String fileName) {
amazonS3.putObject(
new PutObjectRequest(bucket, fileName, uploadFile).withCannedAcl(CannedAccessControlList.PublicRead));
return amazonS3.getUrl(bucket, fileName).toString();
private boolean isImageFile(File file) {
String fileName = file.getName();
String extension = fileName.substring(fileName.lastIndexOf(".") + 1);

return isImageFileExtension(extension);
}

private Optional<File> convert(MultipartFile file) throws ImageException {
String fileExtension = extractFileExtension(file);
checkAllowedImageFileExtension(fileExtension);
private PutObjectRequest addMetadataToRequest(PutObjectRequest request) {
ObjectMetadata objMeta = new ObjectMetadata();
objMeta.setContentType(CONTENT_TYPE);

return request.withMetadata(objMeta);
}

private File convert(MultipartFile file) throws ImageException {
String fileExtension = extractFileExtension(file);
File convertFile = new File(System.getProperty("user.dir") + "/" + UUID.randomUUID() + "." + fileExtension);
log.info("converted file name: {}", convertFile.getName());

try {
log.info("convert try start");
if (convertFile.createNewFile()) { // 바로 위에서 지정한 경로에 File이 생성됨 (경로가 잘못되었다면 생성 불가능)
FileOutputStream fos = new FileOutputStream(convertFile); // FileOutputStream 데이터를 파일에 바이트 스트림으로 저장하기 위함
fos.write(file.getBytes());
fos.close();
log.info("convert to " + convertFile);
return Optional.of(convertFile);
}
FileOutputStream fos = new FileOutputStream(convertFile);
fos.write(file.getBytes());
fos.close();

return convertFile;
} catch (IOException e) {
log.error("convert 실패", e);
throw new ImageException(ErrorCode.IMAGE_PROCESSING_FAIL);
}
log.info("convert empty");
return Optional.empty();
}
}
6 changes: 2 additions & 4 deletions src/main/java/org/cotato/csquiz/common/util/FileUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ public static String extractFileExtension(MultipartFile file) throws ImageExcept
return originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
}

public static void checkAllowedImageFileExtension(String fileExtension) throws ImageException {
if (!Arrays.asList(ALLOWED_IMAGE_FILE_EXTENSIONS).contains(fileExtension)) {
throw new ImageException(ErrorCode.FILE_EXTENSION_FAULT);
}
public static boolean isImageFileExtension(String fileExtension) {
return Arrays.asList(ALLOWED_IMAGE_FILE_EXTENSIONS).contains(fileExtension);
Youthhing marked this conversation as resolved.
Show resolved Hide resolved
}
}
Loading