-
Notifications
You must be signed in to change notification settings - Fork 0
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
chore: ImageUpload api 구현 #15
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package core.kobaco; | ||
|
||
import lombok.Getter; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.http.ResponseEntity; | ||
@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); | ||
} | ||
} |
71 changes: 71 additions & 0 deletions
71
kobaco/kobaco/src/main/java/core/kobaco/Config/SwaggerConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package core.kobaco.Config; | ||
|
||
|
||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
|
||
|
||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; | ||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; | ||
import springfox.documentation.builders.PathSelectors; | ||
import springfox.documentation.builders.RequestHandlerSelectors; | ||
import springfox.documentation.spi.DocumentationType; | ||
import springfox.documentation.spring.web.plugins.Docket; | ||
import springfox.documentation.swagger.web.UiConfiguration; | ||
import springfox.documentation.swagger.web.UiConfigurationBuilder; | ||
import springfox.documentation.swagger2.annotations.EnableSwagger2; | ||
|
||
import java.util.function.Predicate; | ||
|
||
@Configuration // 스프링 실행시 설정파일 읽어드리기 위한 어노테이션 | ||
@EnableSwagger2 // Swagger2를 사용하겠다는 어노테이션 | ||
@SuppressWarnings("unchecked") // warning밑줄 제거를 위한 태그 | ||
|
||
public class SwaggerConfig extends WebMvcConfigurationSupport { | ||
//리소스 핸들러 설 | ||
@Override | ||
public void addResourceHandlers(ResourceHandlerRegistry registry) { | ||
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); | ||
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); | ||
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); | ||
} | ||
|
||
|
||
@Bean | ||
public Docket ImageUploadApi() { | ||
return getDocket("이미지업로드", PathSelectors.regex("/ImageUpload.*")); | ||
} | ||
|
||
@Bean | ||
public Docket recommendApi() { | ||
return getDocket("추천", PathSelectors.regex("/recommend.*")); | ||
} | ||
|
||
@Bean | ||
public Docket relatedRecommendApi() { | ||
return getDocket("관련영상추천", PathSelectors.regex("/relatedRecommend.*")); | ||
} | ||
|
||
@Bean | ||
public Docket allApi() { | ||
return getDocket("전체", PathSelectors.regex("/*.*")); | ||
} | ||
|
||
public Docket getDocket(String groupName, Predicate<String> predicate) { | ||
return new Docket(DocumentationType.SWAGGER_2) | ||
.groupName(groupName) | ||
.select() | ||
.apis(RequestHandlerSelectors.basePackage("core.kobaco")) | ||
.paths(predicate) | ||
.apis(RequestHandlerSelectors.any()) | ||
.build(); | ||
} | ||
|
||
@Bean | ||
public UiConfiguration uiConfig() { | ||
return UiConfigurationBuilder.builder() | ||
.displayRequestDuration(true) | ||
.validatorUrl("") | ||
.build(); | ||
} | ||
} |
33 changes: 33 additions & 0 deletions
33
kobaco/kobaco/src/main/java/core/kobaco/ImageUpload/AwsS3Config.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package core.kobaco.ImageUpload; | ||
|
||
import com.amazonaws.auth.AWSStaticCredentialsProvider; | ||
import com.amazonaws.auth.BasicAWSCredentials; | ||
import com.amazonaws.services.s3.AmazonS3Client; | ||
import com.amazonaws.services.s3.AmazonS3ClientBuilder; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
|
||
|
||
@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(); | ||
} | ||
} | ||
|
30 changes: 30 additions & 0 deletions
30
kobaco/kobaco/src/main/java/core/kobaco/ImageUpload/AwsS3Controller.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package core.kobaco.ImageUpload; | ||
|
||
import core.kobaco.ApiResponse; | ||
import io.swagger.annotations.ApiParam; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.web.bind.annotation.*; | ||
import java.util.List; | ||
import io.swagger.annotations.ApiOperation; | ||
import org.springframework.web.multipart.MultipartFile; | ||
|
||
@RestController | ||
@RequiredArgsConstructor | ||
@RequestMapping("/s3") | ||
public class AwsS3Controller { | ||
private final AwsS3Service awsS3Service; | ||
|
||
@ApiOperation(value = "Amazon S3에 이미지 업로드", notes = "Amazon S3에 이미지 업로드 ") | ||
@PostMapping("/image") | ||
public ResponseEntity<List<String>> uploadImage(@ApiParam(value="img 파일들(여러 파일 업로드 가능)", required = true) @RequestPart List<MultipartFile> multipartFile) { | ||
return ApiResponse.success(awsS3Service.uploadImage(multipartFile)); | ||
} | ||
|
||
@ApiOperation(value = "Amazon S3에 업로드 된 파일을 삭제", notes = "Amazon S3에 업로드된 이미지 삭제") | ||
@DeleteMapping("/image") | ||
public ResponseEntity<Void> deleteImage(@ApiParam(value="img 파일 하나 삭제", required = true) @RequestParam String fileName) { | ||
awsS3Service.deleteImage(fileName); | ||
return ApiResponse.success(null); | ||
} | ||
} |
66 changes: 66 additions & 0 deletions
66
kobaco/kobaco/src/main/java/core/kobaco/ImageUpload/AwsS3Service.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package core.kobaco.ImageUpload; | ||
|
||
import com.amazonaws.services.s3.AmazonS3; | ||
import com.amazonaws.services.s3.model.CannedAccessControlList; | ||
import com.amazonaws.services.s3.model.DeleteObjectRequest; | ||
import com.amazonaws.services.s3.model.ObjectMetadata; | ||
import com.amazonaws.services.s3.model.PutObjectRequest; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.web.multipart.MultipartFile; | ||
import org.springframework.web.server.ResponseStatusException; | ||
|
||
import java.io.IOException; | ||
import java.io.InputStream; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.UUID; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
public class AwsS3Service { | ||
@Value("${cloud.aws.s3.bucket}") | ||
private String bucket; | ||
|
||
private final AmazonS3 amazonS3; | ||
|
||
public List<String> uploadImage(List<MultipartFile> multipartFile) { | ||
List<String> fileNameList = new ArrayList<>(); | ||
|
||
multipartFile.forEach(file -> { | ||
String fileName = createFileName(file.getOriginalFilename()); | ||
ObjectMetadata objectMetadata = new ObjectMetadata(); | ||
objectMetadata.setContentLength(file.getSize()); | ||
objectMetadata.setContentType(file.getContentType()); | ||
|
||
try(InputStream inputStream = file.getInputStream()) { | ||
amazonS3.putObject(new PutObjectRequest(bucket, fileName, inputStream, objectMetadata) | ||
.withCannedAcl(CannedAccessControlList.PublicRead)); | ||
} catch(IOException e) { | ||
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "이미지 업로드에 실패했습니다."); | ||
} | ||
|
||
fileNameList.add(fileName); | ||
}); | ||
|
||
return fileNameList; | ||
} | ||
|
||
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 ResponseStatusException(HttpStatus.BAD_REQUEST, "잘못된 형식의 파일(" + fileName + ") 입니다."); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
우선 패키지 먼저 정리하자
일단 내가 생각하는 패키지 구조는
이렇게 생각중이야
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
그래서 일단 이미지 업로드 패키지를 common에다가 둬서
이렇게 인터페이스만 정의하고
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
그 구현체들은 infra 패키지에 구현을 해주면 좋을 것 같아. 어떻게 생각해?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이게 훨씬 깔끔하겠다. 그러면 다시 패키지 정리해서 올릴게!