◎ 문제 상황
- Spring 환경에서 spring-cloud-starter-aws 를 이용하여 이미지를 업로드 함
- 이미지가 정상적으로 업로드 되었으나, 제공해준 링크를 통해 PC에서 파일이 열리지 않음
◎ 해결 방법
◎ 해결 완료한 Code
@RequiredArgsConstructor
@Service
public class S3UploadImpl implements S3Upload {
...
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss-SSS");
private static final String CONTENT_TYPE = "multipart/formed-data";
@Value("${cloud.aws.s3.bucket}") private String bucket;
@Value("${cloud.aws.s3.dir}") private String dir;
private final AmazonS3Client s3Client;
@Override
public String uploadImage(InputStream inputStream, String originFileName, String fileSize) {
if(!isAllowedExtension(originFileName)){
throw new BusinessLogicException(ExceptionCode.NOT_IMAGE_EXTENSION);
}
String s3FileName = dir + "/" + LocalDateTime.now().format(DATE_FORMAT) + "-" + originFileName;
s3Client.putObject(bucket, s3FileName, inputStream, makeObjectMetadata(fileSize));
return s3Client.getUrl(bucket, s3FileName).toString();
}
...
private ObjectMetadata makeObjectMetadata(String fileSize) {
ObjectMetadata objMeta = new ObjectMetadata();
objMeta.setContentLength(Long.parseLong(fileSize));
objMeta.setContentType(CONTENT_TYPE);
return objMeta;
}
}