Skip to content

Commit

Permalink
#9 feat : S3 파일 관리 메소드 작성
Browse files Browse the repository at this point in the history
- 이미지 업로드 - 이미지 공개 url을 반환
- 파일 업로드
- 파일 다운로드
- MultiPart -> File 변환 메소드
  • Loading branch information
sim-mer committed May 10, 2024
1 parent 3eeff95 commit 452f2d8
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/main/java/gdsc/comunity/service/S3FileService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package gdsc.comunity.service;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import gdsc.comunity.exception.CustomException;
import gdsc.comunity.exception.ErrorCode;
import java.io.File;
import java.util.UUID;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class S3FileService {
private final AmazonS3 s3Client;

private final String bucketName = "mohaji";

public S3FileService() {
this.s3Client = AmazonS3ClientBuilder.defaultClient();
}

public String uploadImage(MultipartFile image){
String s3FileName = UUID.randomUUID().toString().substring(0, 10) + "_" + image.getOriginalFilename();
try {
File convertedFile = convertMultiPartFileToFile(image);
s3Client.putObject(new PutObjectRequest(bucketName, s3FileName, convertedFile)
.withCannedAcl(CannedAccessControlList.PublicRead));
} catch (Exception e) {
throw new CustomException(ErrorCode.FILE_UPLOAD_ERROR);
}

return s3Client.getUrl(bucketName, s3FileName).toString();
}

public String uploadFile(MultipartFile file) {
String s3FileName = UUID.randomUUID().toString().substring(0, 10) + "_" + file.getOriginalFilename();
try {
File convertedFile = convertMultiPartFileToFile(file);
s3Client.putObject(new PutObjectRequest(bucketName, s3FileName, convertedFile));
} catch (Exception e) {
throw new CustomException(ErrorCode.FILE_UPLOAD_ERROR);
}
return s3FileName;
}

public File downloadFile(String s3FileName) {
try {
File file = File.createTempFile(s3FileName.substring(11), null);
s3Client.getObject(new GetObjectRequest(bucketName, s3FileName), file);
return file;
} catch (Exception e) {
throw new CustomException(ErrorCode.FILE_DOWNLOAD_ERROR);
}
}

private File convertMultiPartFileToFile(MultipartFile file) {
File convertedFile = new File(file.getOriginalFilename());
try {
file.transferTo(convertedFile);
} catch (Exception e) {
throw new CustomException(ErrorCode.FILE_TRANSFORM_ERROR);
}
return convertedFile;
}

}

0 comments on commit 452f2d8

Please sign in to comment.