diff --git a/src/main/java/com/loveloveshot/configuration/WebConfig.java b/src/main/java/com/loveloveshot/configuration/WebConfig.java index 2aa4b17..11d8b64 100644 --- a/src/main/java/com/loveloveshot/configuration/WebConfig.java +++ b/src/main/java/com/loveloveshot/configuration/WebConfig.java @@ -21,4 +21,13 @@ public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(resourceHandler) .addResourceLocations(resourceLocation); } + +// @Override +// public void addCorsMappings(CorsRegistry registry) { +// // 모든 uri에 대해 http://localhost:18080, http://localhost:8180 도메인은 접근을 허용한다. +// registry.addMapping("/**") +// .allowedOrigins("http://localhost:3000", "https://loveloveshot.com", "http://192.168.0.12:3000") +// .allowedMethods("GET", "POST") +// .allowCredentials(true); +// } } diff --git a/src/main/java/com/loveloveshot/configuration/WebFluxConfig.java b/src/main/java/com/loveloveshot/configuration/WebFluxConfig.java new file mode 100644 index 0000000..1e690b9 --- /dev/null +++ b/src/main/java/com/loveloveshot/configuration/WebFluxConfig.java @@ -0,0 +1,14 @@ +package com.loveloveshot.configuration; + +import org.springframework.context.annotation.Configuration; +import org.springframework.http.codec.ServerCodecConfigurer; +import org.springframework.web.reactive.config.WebFluxConfigurer; + +@Configuration +public class WebFluxConfig implements WebFluxConfigurer { + + @Override + public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { + configurer.defaultCodecs().maxInMemorySize(-1); //10MB + } +} diff --git a/src/main/java/com/loveloveshot/image/command/application/controller/ImageCommandController.java b/src/main/java/com/loveloveshot/image/command/application/controller/ImageCommandController.java index f4cca07..b998bfe 100644 --- a/src/main/java/com/loveloveshot/image/command/application/controller/ImageCommandController.java +++ b/src/main/java/com/loveloveshot/image/command/application/controller/ImageCommandController.java @@ -1,64 +1,112 @@ package com.loveloveshot.image.command.application.controller; import com.loveloveshot.common.response.ApiResponse; -import com.loveloveshot.image.command.application.dto.SingleImageRequest; +import com.loveloveshot.image.command.application.dto.request.ImageRequest; +import com.loveloveshot.image.command.application.dto.request.SaveRequest; import com.loveloveshot.image.command.application.service.ImageCommandService; import lombok.RequiredArgsConstructor; +import org.springframework.core.io.Resource; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import java.io.File; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; @RestController @RequestMapping("/api/v1") @RequiredArgsConstructor -@CrossOrigin(origins = {"*"}) +@CrossOrigin(origins = {"http://loveloveshot.com", "http://192.168.0.12:3000", "*"}) public class ImageCommandController { - private final ImageCommandService imageCommandService; - @PostMapping(value = "/singleImage") - // 필기. RequestParam에 name값을 지정해주지 않으면 디폴트로 변수명을 key값으로 가짐. - public ResponseEntity uploadSingleImage(@RequestParam MultipartFile maleSingleImage, - @RequestParam MultipartFile femaleSingleImage, - SingleImageRequest singleImageDTO) throws IOException { - singleImageDTO.setMaleSingleImage(maleSingleImage); - singleImageDTO.setFemaleSingleImage(femaleSingleImage); + // 일반 이미지 업로드 + @PostMapping(value = "/uploadStandardImage") + public ResponseEntity uploadStandardImage(@RequestParam MultipartFile maleImage, + @RequestParam MultipartFile femaleImage, + ImageRequest imageRequest) { + List maleImages = new ArrayList<>(); + List femaleImages = new ArrayList<>(); - if (maleSingleImage.isEmpty() || femaleSingleImage.isEmpty()) { - throw new IllegalArgumentException("사진을 첨부해주세요"); + try { + if (maleImage.isEmpty() || femaleImage.isEmpty()) { + throw new NullPointerException("사진을 첨부해 주세요"); + } + if (!maleImage.getContentType().startsWith("image") || + !femaleImage.getContentType().startsWith("image")) { + throw new IllegalArgumentException("이미지 형식의 파일을 올려주세요"); + } + } catch (NullPointerException | IllegalArgumentException e) { + e.printStackTrace(); } + maleImages.add(0, maleImage.getResource()); + femaleImages.add(0, femaleImage.getResource()); + imageRequest.setMaleImages(maleImages); + imageRequest.setFemaleImages(femaleImages); + + return ResponseEntity.ok(ApiResponse.success("성공적으로 업로드 되었습니다. " + , imageCommandService.uploadStandardImage(imageRequest))); + } + + // 일반 AI 이미지 저장 + @PostMapping("/saveAiImage") + public ResponseEntity saveAiImages(@RequestPart(value = "file", required = false) MultipartFile aiImage, + @RequestPart(value = "task_id", required = false) String taskId, + SaveRequest saveRequest) throws IOException { + System.out.println("aiImage = " + aiImage); + System.out.println("taskId = " + taskId); + List files = new ArrayList<>(); - // 설명. 파일 확장자 이미지 형식인지 확인 - if (!maleSingleImage.getContentType().startsWith("image") || - !femaleSingleImage.getContentType().startsWith("image")) { - throw new IllegalArgumentException("이미지 형식의 파일을 올려주세요"); + String filePath = System.getProperty("user.dir") + "/src/main/webapp/AiImages/"; // Ai 이미지 로컬 저장 경로 + + File dir = new File(filePath); + if (!dir.exists()) { + dir.mkdirs(); } - Long userNo = 1L; //임의 값 + String originFileName = aiImage.getOriginalFilename(); + String ext = originFileName.substring(originFileName.lastIndexOf(".")); + String savedName = UUID.randomUUID().toString().replaceAll("-", "") + ext; + + File targetFile = new File(filePath + "/" + savedName); // 저장할 파일 객체 생성 + try { + aiImage.transferTo(targetFile); + } catch (IOException e) { + new File(filePath + "/" + savedName).delete(); + } + files.add(0, targetFile); + System.out.println("targetFile = " + targetFile); + saveRequest.setAiImage(targetFile); + saveRequest.setTaskId(taskId); - return ResponseEntity.ok(ApiResponse.success("성공적으로 등록되었습니다." - , imageCommandService.createAISingleImage(userNo, singleImageDTO))); + return ResponseEntity.ok(ApiResponse.success("성공적으로 저장 되었습니다." + , imageCommandService.saveStandardImage(saveRequest))); } + // 프리미엄 이미지 업로드 + @PostMapping("/uploadPremiumImage") + public ResponseEntity uploadImageList(@RequestParam List maleImages, + @RequestParam List femaleImages, + ImageRequest imageRequest) { + List maleImageResources = getMultipartFile(maleImages); + List femaleImageResources = getMultipartFile(femaleImages); -// @PostMapping("/imageList") -// public void uploadImageList(@RequestParam List maleImageList, -// @RequestParam List femaleImageList, -// ImageListRequestDTO imageListDTO) { -// -// imageListDTO.setMaleImageList(maleImageList); -// imageListDTO.setFemaleImageList(femaleImageList); -// -// if(maleImageList.size() < 2 || maleImageList.size() > 20) { -// throw new IllegalArgumentException("2~20장의 사진을 올려주세요"); -// } -// -// if(femaleImageList.size() < 2 || femaleImageList.size() > 20) { -// throw new IllegalArgumentException("2~20장의 사진을 올려주세요"); -// } -// -// imageCommandService.transferImageList(imageListDTO); -// } + imageRequest.setMaleImages(maleImageResources); + imageRequest.setFemaleImages(femaleImageResources); + + return ResponseEntity.ok(ApiResponse.success("성공적으로 업로드 되었습니다." + , imageCommandService.uploadPremiumImages(imageRequest))); + } + + private List getMultipartFile(List images) { + List imageResources = new ArrayList<>(); + + for (MultipartFile image : images) { + imageResources.add(image.getResource()); + } + return imageResources; + } } diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/ImageListRequest.java b/src/main/java/com/loveloveshot/image/command/application/dto/ImageListRequest.java deleted file mode 100644 index 9337939..0000000 --- a/src/main/java/com/loveloveshot/image/command/application/dto/ImageListRequest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.loveloveshot.image.command.application.dto; - -import lombok.*; -import org.springframework.web.multipart.MultipartFile; - -import java.util.List; - -@Getter -@Setter -@NoArgsConstructor -@AllArgsConstructor -@ToString -public class ImageListRequest { - - private List maleImageList; - private List femaleImageList; -} diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/ImageResponse.java b/src/main/java/com/loveloveshot/image/command/application/dto/ImageResponse.java deleted file mode 100644 index 8b0f001..0000000 --- a/src/main/java/com/loveloveshot/image/command/application/dto/ImageResponse.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.loveloveshot.image.command.application.dto; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.RequiredArgsConstructor; - -import java.io.Serializable; - -@Getter -@RequiredArgsConstructor -@NoArgsConstructor(force = true) -public class ImageResponse implements Serializable { - // private final File aiImage; - private final String aiImage; -} diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/ImagesDTO.java b/src/main/java/com/loveloveshot/image/command/application/dto/ImagesDTO.java deleted file mode 100644 index 40e88cf..0000000 --- a/src/main/java/com/loveloveshot/image/command/application/dto/ImagesDTO.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.loveloveshot.image.command.application.dto; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -@Getter -@Setter -@NoArgsConstructor -@AllArgsConstructor -public class ImagesDTO { - private String maleImage; - private String femaleImage; -} diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/SingleImageRequest.java b/src/main/java/com/loveloveshot/image/command/application/dto/SingleImageRequest.java deleted file mode 100644 index a053121..0000000 --- a/src/main/java/com/loveloveshot/image/command/application/dto/SingleImageRequest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.loveloveshot.image.command.application.dto; - -import lombok.*; -import org.springframework.web.multipart.MultipartFile; - -@Getter -@Setter -@NoArgsConstructor -@AllArgsConstructor -@ToString -public class SingleImageRequest { - - private MultipartFile maleSingleImage; - private MultipartFile femaleSingleImage; -} diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/request/FindRequest.java b/src/main/java/com/loveloveshot/image/command/application/dto/request/FindRequest.java new file mode 100644 index 0000000..4e7f66a --- /dev/null +++ b/src/main/java/com/loveloveshot/image/command/application/dto/request/FindRequest.java @@ -0,0 +1,12 @@ +package com.loveloveshot.image.command.application.dto.request; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +@NoArgsConstructor(force = true) +public class FindRequest { + private final String taskId; +} diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/request/ImageRequest.java b/src/main/java/com/loveloveshot/image/command/application/dto/request/ImageRequest.java new file mode 100644 index 0000000..8e53851 --- /dev/null +++ b/src/main/java/com/loveloveshot/image/command/application/dto/request/ImageRequest.java @@ -0,0 +1,17 @@ +package com.loveloveshot.image.command.application.dto.request; + +import lombok.*; +import org.springframework.core.io.Resource; + +import java.io.Serializable; +import java.util.List; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@ToString +public class ImageRequest implements Serializable { + private List maleImages; + private List femaleImages; +} diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/request/SaveRequest.java b/src/main/java/com/loveloveshot/image/command/application/dto/request/SaveRequest.java new file mode 100644 index 0000000..2dcada6 --- /dev/null +++ b/src/main/java/com/loveloveshot/image/command/application/dto/request/SaveRequest.java @@ -0,0 +1,15 @@ +package com.loveloveshot.image.command.application.dto.request; + +import lombok.*; + +import java.io.File; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@ToString +public class SaveRequest { + private File aiImage; + private String taskId; +} diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/response/FindResponse.java b/src/main/java/com/loveloveshot/image/command/application/dto/response/FindResponse.java new file mode 100644 index 0000000..cb24cad --- /dev/null +++ b/src/main/java/com/loveloveshot/image/command/application/dto/response/FindResponse.java @@ -0,0 +1,14 @@ +package com.loveloveshot.image.command.application.dto.response; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +@NoArgsConstructor(force = true) +public class FindResponse { + private final String imageName; + private final String imagePath; + private final String taskId; +} diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/AiImageResponse.java b/src/main/java/com/loveloveshot/image/command/application/dto/response/SaveResponse.java similarity index 71% rename from src/main/java/com/loveloveshot/image/command/application/dto/AiImageResponse.java rename to src/main/java/com/loveloveshot/image/command/application/dto/response/SaveResponse.java index c46643a..b0fc4ce 100644 --- a/src/main/java/com/loveloveshot/image/command/application/dto/AiImageResponse.java +++ b/src/main/java/com/loveloveshot/image/command/application/dto/response/SaveResponse.java @@ -1,4 +1,4 @@ -package com.loveloveshot.image.command.application.dto; +package com.loveloveshot.image.command.application.dto.response; import lombok.Getter; import lombok.NoArgsConstructor; @@ -10,8 +10,6 @@ @Getter @RequiredArgsConstructor @NoArgsConstructor(force = true) -public class AiImageResponse implements Serializable { - +public class SaveResponse implements Serializable { private final MultipartFile aiImage; - } diff --git a/src/main/java/com/loveloveshot/image/command/application/dto/response/UploadResponse.java b/src/main/java/com/loveloveshot/image/command/application/dto/response/UploadResponse.java new file mode 100644 index 0000000..88f2eeb --- /dev/null +++ b/src/main/java/com/loveloveshot/image/command/application/dto/response/UploadResponse.java @@ -0,0 +1,13 @@ +package com.loveloveshot.image.command.application.dto.response; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +@NoArgsConstructor(force = true) +public class UploadResponse { + private final String status; + private final String taskId; +} diff --git a/src/main/java/com/loveloveshot/image/command/application/service/ImageCommandService.java b/src/main/java/com/loveloveshot/image/command/application/service/ImageCommandService.java index 6677a86..c696731 100644 --- a/src/main/java/com/loveloveshot/image/command/application/service/ImageCommandService.java +++ b/src/main/java/com/loveloveshot/image/command/application/service/ImageCommandService.java @@ -1,12 +1,15 @@ package com.loveloveshot.image.command.application.service; -import com.loveloveshot.image.command.application.dto.ImageResponse; -import com.loveloveshot.image.command.application.dto.SingleImageRequest; +import com.loveloveshot.image.command.application.dto.request.ImageRequest; +import com.loveloveshot.image.command.application.dto.request.SaveRequest; +import com.loveloveshot.image.command.application.dto.response.UploadResponse; +import com.loveloveshot.image.command.domain.aggregate.entity.AiImage; import com.loveloveshot.image.command.domain.repository.ImageCommandRepository; import com.loveloveshot.image.command.domain.service.ImageCommandDomainService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import java.io.File; import java.io.IOException; @Service @@ -16,38 +19,26 @@ public class ImageCommandService { private final ImageCommandDomainService imageCommandDomainService; private final ImageCommandRepository imageCommandRepository; + // 일반 이미지 업로드 + public UploadResponse uploadStandardImage(ImageRequest imageRequest) { + return imageCommandDomainService.uploadStandardImage(imageRequest); + } - public ImageResponse createAISingleImage(Long userNo, SingleImageRequest singleImageDTO) throws IOException { - - ImageResponse aiImageDTO = imageCommandDomainService.getAISingleImage(singleImageDTO); - -// String filePath = "C:\\AIImages/"; -// -// File dir = new File(filePath); -// if (!dir.exists()) { -// dir.mkdirs(); //폴더 없을 시 자동으로 하위폴더 생성 -// } -// -// String originFileName = aiImageDTO.getAiImage().getOriginalFilename(); //원본 파일 이름 -// String ext = originFileName.substring(originFileName.lastIndexOf(".") + 1); //파일 확장자 -// String savedName = UUID.randomUUID().toString().replaceAll("-", "") + "." + ext; //저장되는 이름 -// -// try { -// aiImageDTO.getAiImage().transferTo(new File(filePath + savedName)); -// -// Image image = Image.builder() -// .originImageName(originFileName) -// .savedImageName(savedName) -// .imagePath(filePath) -// .userVO(new UserVO(userNo)) -// .build(); -// -// imageCommandRepository.save(image); -// -// } catch (IOException e) { -// new File(filePath + savedName).delete(); //업로드 후 DB저장 중 오류났을 때 업로드된 이미지 삭제해줌 -// } - - return aiImageDTO; + // 일반 AI 이미지 저장 + public UploadResponse saveStandardImage(SaveRequest saveRequest) throws IOException { + AiImage aiImage = AiImage.builder() + .imageName(saveRequest.getAiImage().getName()) + .imagePath(saveRequest.getAiImage().getPath()) + .taskId(saveRequest.getTaskId()) + .build(); + imageCommandRepository.save(aiImage); + return new UploadResponse(); } + + // 프리미엄 이미지 업로드 + public UploadResponse uploadPremiumImages(ImageRequest imageRequest) { + + return imageCommandDomainService.uploadPremiumImages(imageRequest); + } + } diff --git a/src/main/java/com/loveloveshot/image/command/domain/aggregate/entity/AiImage.java b/src/main/java/com/loveloveshot/image/command/domain/aggregate/entity/AiImage.java new file mode 100644 index 0000000..a4e3e30 --- /dev/null +++ b/src/main/java/com/loveloveshot/image/command/domain/aggregate/entity/AiImage.java @@ -0,0 +1,36 @@ +package com.loveloveshot.image.command.domain.aggregate.entity; + +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Entity +@Table(name = "TBL_AI_IMAGE") +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class AiImage { + @Id + @Column + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long aiImageNo; + + @Column + private String taskId; + + @Column + private String imageName; + + @Column + private String imagePath; + + @Builder + public AiImage(Long aiImageNo, String taskId, String imageName, String imagePath) { + this.aiImageNo = aiImageNo; + this.taskId = taskId; + this.imageName = imageName; + this.imagePath = imagePath; + } +} diff --git a/src/main/java/com/loveloveshot/image/command/domain/repository/ImageCommandRepository.java b/src/main/java/com/loveloveshot/image/command/domain/repository/ImageCommandRepository.java index c713c0b..8600cc4 100644 --- a/src/main/java/com/loveloveshot/image/command/domain/repository/ImageCommandRepository.java +++ b/src/main/java/com/loveloveshot/image/command/domain/repository/ImageCommandRepository.java @@ -1,9 +1,9 @@ package com.loveloveshot.image.command.domain.repository; -import com.loveloveshot.image.command.domain.aggregate.entity.Image; +import com.loveloveshot.image.command.domain.aggregate.entity.AiImage; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository -public interface ImageCommandRepository extends JpaRepository { +public interface ImageCommandRepository extends JpaRepository { } diff --git a/src/main/java/com/loveloveshot/image/command/domain/service/ImageCommandDomainService.java b/src/main/java/com/loveloveshot/image/command/domain/service/ImageCommandDomainService.java index 8815531..0c8219d 100644 --- a/src/main/java/com/loveloveshot/image/command/domain/service/ImageCommandDomainService.java +++ b/src/main/java/com/loveloveshot/image/command/domain/service/ImageCommandDomainService.java @@ -1,15 +1,15 @@ package com.loveloveshot.image.command.domain.service; import com.loveloveshot.common.annotation.DomainService; -import com.loveloveshot.image.command.application.dto.ImageResponse; -import com.loveloveshot.image.command.application.dto.SingleImageRequest; - -import java.io.IOException; +import com.loveloveshot.image.command.application.dto.request.ImageRequest; +import com.loveloveshot.image.command.application.dto.response.UploadResponse; @DomainService public interface ImageCommandDomainService { - ImageResponse getAISingleImage(SingleImageRequest singleImageDTO) throws IOException; + UploadResponse uploadStandardImage(ImageRequest imageRequest); + + UploadResponse uploadPremiumImages(ImageRequest imageRequest); // void getAIImageList(ImageListRequestDTO imageListDTO); } diff --git a/src/main/java/com/loveloveshot/image/command/infrastructure/service/HttpPostMultipart.java b/src/main/java/com/loveloveshot/image/command/infrastructure/service/HttpPostMultipart.java deleted file mode 100644 index 9c7bbc9..0000000 --- a/src/main/java/com/loveloveshot/image/command/infrastructure/service/HttpPostMultipart.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.loveloveshot.image.command.infrastructure.service; - -import java.io.*; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; -import java.util.Map; -import java.util.UUID; - -public class HttpPostMultipart { - private static final String LINE = "\r\n"; - private final String boundary; - private final HttpURLConnection httpConn; - private final String charset; - private final OutputStream outputStream; - private final PrintWriter writer; - - /** - * This constructor initializes a new HTTP POST request with content type - * is set to multipart/form-data - * - * @param requestURL - * @param charset - * @param headers - * @throws IOException - */ - public HttpPostMultipart(String requestURL, String charset, Map headers) throws IOException { - this.charset = charset; - boundary = UUID.randomUUID().toString(); - URL url = new URL(requestURL); - httpConn = (HttpURLConnection) url.openConnection(); - httpConn.setUseCaches(false); - httpConn.setDoOutput(true); // indicates POST method - httpConn.setDoInput(true); - httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); - if (headers != null && headers.size() > 0) { - for (String key : headers.keySet()) { - String value = headers.get(key); - httpConn.setRequestProperty(key, value); - } - } - outputStream = httpConn.getOutputStream(); - writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); - } - - /** - * Adds a form field to the request - * - * @param name field name - * @param value field value - */ - public void addFormField(String name, String value) { - writer.append("--").append(boundary).append(LINE); - writer.append("Content-Disposition: form-data; name=\"").append(name).append("\"").append(LINE); - writer.append("Content-Type: text/plain; charset=").append(charset).append(LINE); - writer.append(LINE); - writer.append(value).append(LINE); - writer.flush(); - } - - /** - * Adds a upload file section to the request - * - * @param fieldName - * @param uploadFile - * @throws IOException - */ - public void addFilePart(String fieldName, File uploadFile) - throws IOException { - String fileName = uploadFile.getName(); - writer.append("--").append(boundary).append(LINE); - writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"").append(LINE); - writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(fileName)).append(LINE); - writer.append("Content-Transfer-Encoding: binary").append(LINE); - writer.append(LINE); - writer.flush(); - - FileInputStream inputStream = new FileInputStream(uploadFile); - byte[] buffer = new byte[4096]; - int bytesRead = -1; - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); - } - outputStream.flush(); - inputStream.close(); - writer.append(LINE); - writer.flush(); - } - - /** - * Completes the request and receives response from the server. - * - * @return String as response in case the server returned - * status OK, otherwise an exception is thrown. - * @throws IOException - */ - public String finish() throws IOException { - String response = ""; - writer.flush(); - writer.append("--").append(boundary).append("--").append(LINE); - writer.close(); - - // checks server's status code first - int status = httpConn.getResponseCode(); - if (status == HttpURLConnection.HTTP_OK) { - ByteArrayOutputStream result = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int length; - while ((length = httpConn.getInputStream().read(buffer)) != -1) { - result.write(buffer, 0, length); - } - response = result.toString(this.charset); - httpConn.disconnect(); - } else { - throw new IOException("Server returned non-OK status: " + status); - } - return response; - } -} diff --git a/src/main/java/com/loveloveshot/image/command/infrastructure/service/ImageCommandInfraService.java b/src/main/java/com/loveloveshot/image/command/infrastructure/service/ImageCommandInfraService.java index db2012c..72d1b37 100644 --- a/src/main/java/com/loveloveshot/image/command/infrastructure/service/ImageCommandInfraService.java +++ b/src/main/java/com/loveloveshot/image/command/infrastructure/service/ImageCommandInfraService.java @@ -3,82 +3,80 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.loveloveshot.common.annotation.InfraService; -import com.loveloveshot.image.command.application.dto.ImageResponse; -import com.loveloveshot.image.command.application.dto.SingleImageRequest; +import com.loveloveshot.image.command.application.dto.request.ImageRequest; +import com.loveloveshot.image.command.application.dto.response.UploadResponse; import com.loveloveshot.image.command.domain.service.ImageCommandDomainService; +import org.springframework.core.io.Resource; import org.springframework.http.MediaType; -import org.springframework.http.client.MultipartBodyBuilder; -import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.client.WebClient; -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.util.Base64; -import java.util.UUID; - @InfraService public class ImageCommandInfraService implements ImageCommandDomainService { - private final String REQUEST_URL = "http://192.168.0.36"; // AI 이미지 생성 API URL - private final WebClient WEBCLIENT = WebClient.builder().baseUrl(REQUEST_URL).build(); + private final String REQUEST_URL = "http://192.168.0.198:5001"; // AI 이미지 생성 API URL + private final WebClient WEBCLIENT = WebClient.builder() + .baseUrl(REQUEST_URL) + .build(); + private final int UPLOAD_COUNT = 0; @Override - public ImageResponse getAISingleImage(SingleImageRequest singleImageDTO) throws IOException { - -// HttpURLConnection 방식 -// try { -// // Set header -// Map headers = new HashMap<>(); -// HttpPostMultipart multipart = new HttpPostMultipart(reqURL, "utf-8", headers); -// -// // Add form field -//// multipart.addFormField("username", "test_name"); -//// multipart.addFormField("password", "test_psw"); -// -// // Add file -// multipart.addFilePart("imgFile", new File(imagesDTO.getMaleImage())); -// multipart.addFilePart("imgFile", new File(imagesDTO.getFemaleImage())); -// -// // Print result -// String response = multipart.finish(); -// System.out.println(response); -// } catch (Exception e) { -// e.printStackTrace(); -// } - - // WebClient 방식 - MultipartBodyBuilder formData = new MultipartBodyBuilder(); - formData.part("imgFile", singleImageDTO.getMaleSingleImage().getResource()); - formData.part("imgFile", singleImageDTO.getFemaleSingleImage().getResource()); + public UploadResponse uploadStandardImage(ImageRequest imageRequest) { + Resource maleImages = imageRequest.getMaleImages().get(0); + Resource femaleImages = imageRequest.getFemaleImages().get(0); + MultiValueMap body = new LinkedMultiValueMap<>(); + body.add("male_files", maleImages); + body.add("female_files", femaleImages); String response = WEBCLIENT.post() .uri("/main/standard") // baseUrl 이후 uri - .accept(MediaType.MULTIPART_FORM_DATA) - .contentType(MediaType.MULTIPART_FORM_DATA) // 보내는 자원의 형식(header에 담김) - .body(BodyInserters.fromMultipartData(formData.build())) // 요청 body - .retrieve() // ResponseEntity를 받아 디코딩 + .contentType(MediaType.MULTIPART_FORM_DATA) + .bodyValue(body) // 요청 body + .retrieve() // 디코딩 .bodyToMono(String.class) // 0~1개의 결과 리턴 .block(); // blocking - + System.out.println("response = " + response); JsonElement element = JsonParser.parseString(response); - String fileData = element.getAsJsonObject().get("file_data").getAsString(); - String filePath = "/AiImages/" + UUID.randomUUID() + ".png"; // Ai 이미지 로컬 저장 경로 + String status = element.getAsJsonObject().get("status").getAsString(); + String taskId = element.getAsJsonObject().get("task_id").getAsString(); + System.out.println("status = " + status); + System.out.println("taskId = " + taskId); - // Base64 문자열을 바이트 배열로 변환 - byte[] imageBytes = Base64.getDecoder().decode(fileData); +// List files = new ArrayList<>(); +// String filePath = "src/main/webapp/AiImages/" + UUID.randomUUID() + ".png"; // Ai 이미지 로컬 저장 경로 +// try { +// // 바이트 배열을 파일로 저장 +// FileOutputStream fos = new FileOutputStream(filePath); +// fos.write(response); +// fos.close(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// files.add(0, filePath); +// System.out.println("files = " + files); - // 바이트 배열을 BufferedImage 객체로 변환 - try (ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes)) { - BufferedImage image = ImageIO.read(bis); + // 이미지 AI 서버에서 JSON으로 받는 법 +// JsonElement element = JsonParser.parseString(response); +// String fileData = element.getAsJsonObject().get("file_data").getAsString(); +// +// // Base64 문자열을 바이트 배열로 변환 +// byte[] imageBytes = Base64.getDecoder().decode(fileData); +// +// // 바이트 배열을 BufferedImage 객체로 변환 +// try (ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes)) { +// BufferedImage image = ImageIO.read(bis); +// +// // BufferedImage 객체를 이미지 파일로 저장 +// ImageIO.write(image, "png", new File(filePath)); +// } catch (IOException e) { +// e.printStackTrace(); +// } + return new UploadResponse(status, taskId); + } - // BufferedImage 객체를 이미지 파일로 저장 - ImageIO.write(image, "png", new File("src/main/webapp" + filePath)); - } catch (IOException e) { - e.printStackTrace(); - } - return new ImageResponse(filePath); + @Override + public UploadResponse uploadPremiumImages(ImageRequest imageRequest) { + return null; } // @Override diff --git a/src/main/java/com/loveloveshot/image/query/application/controller/ImageQueryController.java b/src/main/java/com/loveloveshot/image/query/application/controller/ImageQueryController.java new file mode 100644 index 0000000..e0f4528 --- /dev/null +++ b/src/main/java/com/loveloveshot/image/query/application/controller/ImageQueryController.java @@ -0,0 +1,26 @@ +package com.loveloveshot.image.query.application.controller; + +import com.loveloveshot.common.response.ApiResponse; +import com.loveloveshot.image.command.application.dto.request.FindRequest; +import com.loveloveshot.image.query.application.service.ImageQueryService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1") +@RequiredArgsConstructor +@CrossOrigin(origins = {"http://loveloveshot.com", "http://192.168.0.12:3000", "*"}) +public class ImageQueryController { + private final ImageQueryService imageQueryService; + + // 일반 이미지 조회 + @GetMapping("/findAiImage") + public ResponseEntity getStandardAiImage(FindRequest findRequest) { + return ResponseEntity.ok(ApiResponse.success("조회 성공" + , imageQueryService.findStandardAiImage(findRequest))); + } +} diff --git a/src/main/java/com/loveloveshot/image/query/application/controller/test.java b/src/main/java/com/loveloveshot/image/query/application/controller/test.java deleted file mode 100644 index b45fd5b..0000000 --- a/src/main/java/com/loveloveshot/image/query/application/controller/test.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.loveloveshot.image.query.application.controller; - -public class test { -} diff --git a/src/main/java/com/loveloveshot/image/query/application/service/ImageQueryService.java b/src/main/java/com/loveloveshot/image/query/application/service/ImageQueryService.java new file mode 100644 index 0000000..4d3267e --- /dev/null +++ b/src/main/java/com/loveloveshot/image/query/application/service/ImageQueryService.java @@ -0,0 +1,22 @@ +package com.loveloveshot.image.query.application.service; + +import com.loveloveshot.image.command.application.dto.request.FindRequest; +import com.loveloveshot.image.command.application.dto.response.FindResponse; +import com.loveloveshot.image.command.domain.aggregate.entity.AiImage; +import com.loveloveshot.image.query.domain.repository.ImageQueryRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class ImageQueryService { + private final ImageQueryRepository imageQueryRepository; + + // 일반 Ai 이미지 조회 + public FindResponse findStandardAiImage(FindRequest findRequest) { + AiImage aiImage = imageQueryRepository.findAiImageByTaskId(findRequest.getTaskId()); + return new FindResponse(aiImage.getImageName() + , aiImage.getImagePath() + , aiImage.getTaskId()); + } +} diff --git a/src/main/java/com/loveloveshot/image/query/application/service/test.java b/src/main/java/com/loveloveshot/image/query/application/service/test.java deleted file mode 100644 index c1cec6c..0000000 --- a/src/main/java/com/loveloveshot/image/query/application/service/test.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.loveloveshot.image.query.application.service; - -public class test { -} diff --git a/src/main/java/com/loveloveshot/image/query/domain/repository/ImageQueryRepository.java b/src/main/java/com/loveloveshot/image/query/domain/repository/ImageQueryRepository.java new file mode 100644 index 0000000..623bdff --- /dev/null +++ b/src/main/java/com/loveloveshot/image/query/domain/repository/ImageQueryRepository.java @@ -0,0 +1,10 @@ +package com.loveloveshot.image.query.domain.repository; + +import com.loveloveshot.image.command.domain.aggregate.entity.AiImage; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ImageQueryRepository extends JpaRepository { + AiImage findAiImageByTaskId(String taskId); +} diff --git a/src/main/resources/log4j2.yml b/src/main/resources/log4j2.yml index 7b7dab6..6150914 100644 --- a/src/main/resources/log4j2.yml +++ b/src/main/resources/log4j2.yml @@ -7,7 +7,7 @@ Configutation: - name: "log-path" value: "./logs" - name: "pattern" - value: "%highlight{[%-5level]} %d{yyyy-MM-dd HH:mm:ss.SSS} [%t][%F] %c{1} - %msg%n" + value: "%highlight{[%-5level]} %d{yyyy-MM-dd HH:mm:ss.SSS} [%t][%F] %highlight{%c{1}} : %msg%n" - name: "charset-UTF-8" value: "UTF-8" diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index 5ef1718..ed41cce 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -7,16 +7,16 @@

기본 사진 업로드

-
- 남성이미지 :
- 여성이미지 :
+ + 남성이미지 :
+ 여성이미지 :

프리미엄 사진 업로드

-
- 남성이미지 :
- 여성이미지 :
+ + 남성이미지 :
+ 여성이미지 :