Skip to content

Commit

Permalink
Merge pull request #181 from kookmin-sw/refactor/be/#180-dto-mapping
Browse files Browse the repository at this point in the history
Refactor/be/#180 게시글 작성 content-type mapping 및 S3 이미지 용량 제한
  • Loading branch information
mclub4 authored May 12, 2024
2 parents 3faa116 + 81fc489 commit 0dcae42
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,39 +71,39 @@ public List<String> upload(List<MultipartFile> images, Long questionId, boolean
}

private String uploadImage(MultipartFile image) {
this.validateImageFileExtention(image.getOriginalFilename());
this.validateImageFileExtension(image.getOriginalFilename());
try {
return this.uploadImageToS3(image);
} catch (IOException e) {
throw new BusinessException(ErrorCode.IO_EXCEPTION_ON_IMAGE_UPLOAD);
}
}

private void validateImageFileExtention(String filename) {
private void validateImageFileExtension(String filename) {
int lastDotIndex = filename.lastIndexOf(".");
if (lastDotIndex == -1) {
throw new BusinessException(ErrorCode.NO_FILE_EXTENTION);
throw new BusinessException(ErrorCode.NO_FILE_EXTENSION);
}

String extention = filename.substring(lastDotIndex + 1).toLowerCase();
List<String> allowedExtentionList = Arrays.asList("jpg", "jpeg", "png", "gif");
String extension = filename.substring(lastDotIndex + 1).toLowerCase();
List<String> allowedExtensionList = Arrays.asList("jpg", "jpeg", "png", "gif");

if (!allowedExtentionList.contains(extention)) {
throw new BusinessException(ErrorCode.INVALID_FILE_EXTENTION);
if (!allowedExtensionList.contains(extension)) {
throw new BusinessException(ErrorCode.INVALID_FILE_EXTENSION);
}
}

private String uploadImageToS3(MultipartFile image) throws IOException {
String originalFilename = image.getOriginalFilename();
String extention = originalFilename.substring(originalFilename.lastIndexOf("."));
String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

String s3FileName = UUID.randomUUID().toString().substring(0, 10) + originalFilename;

InputStream is = image.getInputStream();
byte[] bytes = IOUtils.toByteArray(is);

ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType("image/" + extention);
metadata.setContentType("image/" + extension);
metadata.setContentLength(bytes.length);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.example.capstone.global.config;

import com.example.capstone.global.converter.OctetStreamReadMsgConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
private OctetStreamReadMsgConverter octetStreamReadMsgConverter;

@Autowired
public WebConfig(OctetStreamReadMsgConverter octetStreamReadMsgConverter) {
this.octetStreamReadMsgConverter = octetStreamReadMsgConverter;
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(octetStreamReadMsgConverter);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.example.capstone.global.converter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;

@Component
public class OctetStreamReadMsgConverter extends AbstractJackson2HttpMessageConverter {
@Autowired
public OctetStreamReadMsgConverter(ObjectMapper objectMapper) {
super(objectMapper, MediaType.APPLICATION_OCTET_STREAM);
}

@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return false;
}

@Override
public boolean canWrite(Type type, Class<?> clazz, MediaType mediaType) {
return false;
}

@Override
protected boolean canWrite(MediaType mediaType) {
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.nio.file.AccessDeniedException;
Expand Down Expand Up @@ -69,6 +71,19 @@ protected ResponseEntity<ApiResult<?>> handleJwtTokenInvalidException(final JwtT
.body(new ApiResult<>(errorCode));
}

/*
* 업로드 파일 용량이 최대 용량보다 초과시 발생
* */
@ExceptionHandler(MultipartException.class)
@ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
protected ResponseEntity<ApiResult<?>> handleMaxUploadSizeExceededException (final MultipartException e){
log.error("handleMaxUploadSizeExceededException", e);
final ErrorCode errorCode = ErrorCode.MAX_SIZE_UPLOAD_EXCEED;
return ResponseEntity
.status(errorCode.getStatus())
.body(new ApiResult<>(errorCode));
}

@ExceptionHandler(RedisConnectionFailureException.class)
protected ResponseEntity<ApiResult<?>> handleRedisConnectionFailureException(final RedisConnectionFailureException e){
log.error("handleJwtTokenInvalid", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ public enum ErrorCode {
// S3 Error
EMPTY_FILE_EXCEPTION(400, "S301", "File is empty"),
IO_EXCEPTION_ON_IMAGE_UPLOAD(400, "S302", "Io exception on image"),
NO_FILE_EXTENTION(400, "S303", "Not found file"),
INVALID_FILE_EXTENTION(400, "S304", "File is invalid"),
NO_FILE_EXTENSION(400, "S303", "Not found file"),
INVALID_FILE_EXTENSION(400, "S304", "File is invalid"),
PUT_OBJECT_EXCEPTION(400, "S305", "Object can not put"),
IO_EXCEPTION_ON_IMAGE_DELETE(400, "S306", "Io exception on image delete"),
MAX_SIZE_UPLOAD_EXCEED(400, "S307", "File size exceeded the max size"),

// HMAC
HMAC_NOT_VALID(403, "HM001", "HMAC is not valid"),
Expand Down
7 changes: 7 additions & 0 deletions back/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ s3.bucket.name=capstone-30-backend
s3.region.static=ap-northeast-2
s3.stack.auto=false

spring.servlet.multipart.resolve-lazily=true
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=500MB

server.tomcat.max-swallow-size=200MB
server.tomcat.max-http-form-post-size=200MB

hmac.secret=${HMAC_SECRET}
hmac.algorithm=${HMAC_ALGORITHM}

Expand Down

0 comments on commit 0dcae42

Please sign in to comment.