Skip to content

Commit

Permalink
Merge pull request #54 from taking/taking
Browse files Browse the repository at this point in the history
Feat: File Upload 기능 추가
  • Loading branch information
taking authored Oct 30, 2023
2 parents 100f664 + cb14de6 commit 85dca6b
Show file tree
Hide file tree
Showing 8 changed files with 59 additions and 23 deletions.
1 change: 0 additions & 1 deletion nw/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,4 @@ dependencies {
implementation 'io.minio:minio-admin:8.5.5'
implementation 'com.fasterxml.jackson.core:jackson-core:2.15.2'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
implementation 'commons-io:commons-io:2.15.0'
}
40 changes: 40 additions & 0 deletions nw/src/main/java/lab/cherry/nw/controller/FileController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import org.bson.types.ObjectId;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
Expand All @@ -17,14 +19,24 @@
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lab.cherry.nw.error.ErrorResponse;
import lab.cherry.nw.error.ResultResponse;
import lab.cherry.nw.error.enums.SuccessCode;
import lab.cherry.nw.model.FileEntity;
import lab.cherry.nw.model.WeddinghallEntity;
import lab.cherry.nw.service.FileService;
import lab.cherry.nw.util.Common;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -96,6 +108,34 @@ public ResponseEntity<?> findByFileId(@PathVariable("id") String id) {
return new ResponseEntity<>(fileService.findById(id), new HttpHeaders(), HttpStatus.OK);
}


/**
* [FileController] 파일 업로드 함수
*
* @param files 파일 업로드 객체 리스트입니다.
* @return
* <pre>
* true : 성공(200)을 반환합니다.
* false : 에러(400)를 반환합니다.
* </pre>
*
* Author : taking(taking@duck.com)
*/
@PostMapping(value = "/upload", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE})
@Operation(summary = "파일 업로드", description = "파일을 업로드합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "파일 업로드가 완료되었습니다.", content = @Content(schema = @Schema(implementation = ResponseEntity.class))),
@ApiResponse(responseCode = "400", description = "입력 값이 잘못되었습니다.", content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
})
public ResponseEntity<?> uploadFile(@RequestPart List<MultipartFile> files) {

log.info("[WeddinghallController] uploadFile...!");

ResultResponse result = ResultResponse.of(SuccessCode.FILE_UPLOAD_SUCCESS, fileService.uploadFiles(new ObjectId().toString(), files));
return new ResponseEntity<>(result, new HttpHeaders(), HttpStatus.OK);
}


/**
* [FileController] 특정 파일 다운로드 함수
*
Expand Down
3 changes: 2 additions & 1 deletion nw/src/main/java/lab/cherry/nw/error/enums/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@ public enum ErrorCode {
INVALID_USERNAME(400, "잘못된 사용자 이름/비밀번호를 입력했습니다."),
INTERNAL_SERVER_ERROR(500, "서버에 문제가 발생했습니다."),
NOT_FOUND(404, "찾을 수 없습니다."),
USER_NOT_FOUND(404, "사용자를 찾을 수 없습니다."),
USER_INVALID_INPUT_VALUE(400, "아이디 또는 비밀번호가 유효하지 않습니다."),
FORBIDDEN(403, "접근 권한이 없어 거부되었습니다."),
ACCESS_DENIED_EXCEPTION(401, "인증 정보가 유효하지 않습니다."),
EXPIRED_EXCEPTION(401, "기간이 만료된 링크입니다."),
USER_DUPLICATE(409, "중복된 사용자가 있습니다."),
USER_NOTFOUND(409, "사용자를 찾을 수 없습니다."),
EMAIL_AUTH_ERROR(409, "이메일 인증이 진행 중이 아니거나, 이메일 코드가 유효하지 않습니다."),
REQUIRE_EMAIL_VERIFIED(409, "이메일 인증을 진행해주세요."),
DUPLICATE(409, "중복된 데이터가 있습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public enum SuccessCode {

// Common
OK(200, "Success"),
FILE_UPLOAD_SUCCESS(200, "파일 업로드 완료"),
REGISTER_SUCCESS(200, "회원가입 완료"),
USERID_CHECK_OK(200, "사용 가능합니다."),
PASSWORD_RESET_OK(200, "비밀번호 초기화 이메일 발송 완료"),
Expand Down
10 changes: 7 additions & 3 deletions nw/src/main/java/lab/cherry/nw/model/UserEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

import org.springframework.web.multipart.MultipartFile;
import java.io.Serializable;
import java.time.Instant;

Expand Down Expand Up @@ -98,6 +98,10 @@ public void emailVerifiedSuccess() {
public void resetPassword(String password) {
this.password = password;
}

public void editImage(Object image) {
this.photo = image;
}

//////////////////////////////////////////////////////////////////////////

Expand All @@ -113,7 +117,7 @@ public static class UserRegisterDto {

@NotBlank
@Schema(title = "사용자 이름", example = "홍길동")
@Size(min = 2, max = 10, message = "Minimum username length: 4 characters")
@Size(min = 2, max = 10, message = "Minimum username length: 2 characters")
private String userName;

@NotBlank
Expand All @@ -127,7 +131,7 @@ public static class UserRegisterDto {

@NotBlank
@Schema(title = "사용자 비밀번호", example = "Pa@sW0rd")
@Size(min = 3, message = "Minimum password length: 8 characters")
@Size(min = 3, message = "Minimum password length: 3 characters")
private String userPassword;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,11 @@ private void authenticateByIdAndPassword(UserEntity.UserLoginDto userLoginDto) {
}

UserEntity user = userRepository.findByuserid(userLoginDto.getUserId())
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND)); // 로그인 정보가 유효하지 않음
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND)); // 로그인 정보가 유효하지 않음

if(!passwordEncoder.matches(userLoginDto.getUserPassword(), user.getPassword())) {
log.error("{} Account Password is Corrent!", userLoginDto.getUserId());
throw new CustomException(ErrorCode.INVALID_INPUT_VALUE); // 로그인 정보가 정확하지 않음
throw new CustomException(ErrorCode.USER_INVALID_INPUT_VALUE); // 로그인 정보가 정확하지 않음
}
}

Expand Down
12 changes: 6 additions & 6 deletions nw/src/main/java/lab/cherry/nw/service/Impl/FileServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import lab.cherry.nw.util.FormatConverter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.bson.types.ObjectId;

@Slf4j
Expand Down Expand Up @@ -116,17 +115,18 @@ public Map<String, Object> downloadFiles(String key, String value) {
resources.forEach((Consumer<GridFSFile>) file -> allFiles.add(file));

log.error("allFiles {}", allFiles);
for(GridFSFile file : allFiles) {
log.error("FileName : {}", file.getFilename());
}
log.error("allFiles.size {}", allFiles.size());

try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
for (GridFSFile file : allFiles) {

String fileName = FilenameUtils.getBaseName(file.getFilename()) + "-" + new ObjectId() + "." + FilenameUtils.getExtension(file.getFilename());
int lastIndex = file.getFilename().lastIndexOf(".");
String fileNameWithoutExtension = file.getFilename().substring(0, lastIndex);
String Extension = file.getFilename().substring(file.getFilename().lastIndexOf(".") + 1);
String fullName = fileNameWithoutExtension + "-" + new ObjectId() + "." + Extension;

ZipEntry zipEntry = new ZipEntry(fileName);
ZipEntry zipEntry = new ZipEntry(fullName);
zipOut.putNextEntry(zipEntry);

byte[] objectData = IOUtils.toByteArray(operations.getResource(file).getInputStream());
Expand Down
11 changes: 1 addition & 10 deletions nw/src/main/java/lab/cherry/nw/service/Impl/UserServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -188,16 +188,7 @@ public void updateUserPhoto(String id, List<MultipartFile> image) {
imageData = fileService.uploadFiles(userEntity.getId(), image).get(0);
}

userEntity = UserEntity.builder()
.id(userEntity.getId())
.userid(userEntity.getUserid())
.username(userEntity.getUsername())
.email(userEntity.getEmail())
.password(userEntity.getPassword())
.org(userEntity.getOrg())
.photo(imageData)
.build();

userEntity.editImage(imageData);
userRepository.save(userEntity);

}
Expand Down

0 comments on commit 85dca6b

Please sign in to comment.