cors 문제는 해결을 했는데 이미지가 올라가지 않았다. 해결법은 aws s3 설정이였다.
https://innovation123.tistory.com/197 님을 참고하였다.
AwsS3Config.java
@Configuration
public class AwsS3Config {
@Value("${cloud.aws.credentials.access-key}")
private String accessKey;
@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;
@Value("${cloud.aws.region.static}")
private String region;
@Bean
public AmazonS3Client amazonS3Client() {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
return (AmazonS3Client) AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
}
}
AmazonS3Controller.java
@RestController
@RequiredArgsConstructor
@RequestMapping("/s3")
@CrossOrigin
public class AmazonS3Controller {
private final AwsS3Service awsS3Service;
@PostMapping("/image")
public ResponseEntity<String> uploadImage(@RequestPart MultipartFile multipartFile) {
return ApiResponse.success(awsS3Service.uploadImage(multipartFile));
}
@DeleteMapping("/image")
public ResponseEntity<Void> deleteImage(@RequestParam String fileName) {
awsS3Service.deleteImage(fileName);
return ApiResponse.success(null);
}
}
ApiResponse.java
@Getter
public class ApiResponse<T> {
public static <T> ResponseEntity<T> success(T body) {
return ResponseEntity.status(HttpStatus.OK).body(body);
}
public static <T> ResponseEntity<T> created(T body) {
return ResponseEntity.status(HttpStatus.CREATED).body(body);
}
public static <T> ResponseEntity<T> fail(T body) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
}
public static <T> ResponseEntity<T> forbidden(T body) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body);
}
}
AwsS3Service.java
@Service
@RequiredArgsConstructor
public class AwsS3Service {
private final AmazonS3 amazonS3;
@Value("${cloud.aws.s3.bucket}")
private String bucket;
public String uploadImage(MultipartFile multipartFile) {
String fileName = createFileName(multipartFile.getOriginalFilename());
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(multipartFile.getSize());
objectMetadata.setContentType(multipartFile.getContentType());
try(InputStream inputStream = multipartFile.getInputStream()) {
amazonS3.putObject(new PutObjectRequest(bucket, fileName, inputStream, objectMetadata)
.withCannedAcl(CannedAccessControlList.PublicRead));
} catch(IOException e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "이미지 업로드에 실패했습니다.");
}
return fileName;
}
public void deleteImage(String fileName) {
amazonS3.deleteObject(new DeleteObjectRequest(bucket, fileName));
}
private String createFileName(String fileName) {
return UUID.randomUUID().toString().concat(getFileExtension(fileName));
}
private String getFileExtension(String fileName) {
try {
return fileName.substring(fileName.lastIndexOf("."));
} catch (StringIndexOutOfBoundsException e) {
throw new IllegalArgumentException(String.format("잘못된 형식의 파일 (%s) 입니다.", fileName));
}
}
}