moasis-team/legacy-monolithic-be

이미지 처리

Closed this issue · 1 comments

  • 업로드
  • 다운로드
  • 리사이징
  • push -> Article Service 병합 후에 적용 예정

MulripartFile

public interface **MultipartFile** extends [InputStreamSource](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/InputStreamSource.html){
	String getName();

	@Nullable String getOriginalFilename();

	@Nullable String getContentType();

	boolean isEmpty();

	long getSize();

	byte[] getBytes() throws IOException;

	@Override
	InputStream getInputStream() throws IOException;

	default Resource getResource() {
		return new MultipartFileResource(this);
	}

	void transferTo(File dest) throws IOException, IllegalStateException;

	default void transferTo(Path dest) throws IOException, IllegalStateException {
		FileCopyUtils.copy(getInputStream(), Files.newOutputStream(dest));
	}
}

A representation of an uploaded file received in a multipart request.

The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storage will be cleared at the end of request processing.

: 보통 파일을 전송 할 때 사용하며 HTTP 프로토콜의 body부분에 데이터를 여러 부분으로 나눠서 보낸다

File Upload

@PostMapping("/file")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file)
  1. 이미지를 처리 할 것이므로 png, jpg, jpeg, gif 의 확장자만 허용, getContentType application/png의 형식으로 저장됨
  2. 파일의 정보(이름, 크기, 시간, 출처)를 DB에 저장하고 transferTo() 메소드를 사용해 프로젝트 패키지에 저장
  3. 파일의 이름이 곂칠 수 있으니 UUID를 붙여 새로운 이름으로 저장(다른 방식도 생각 해 볼 것)
  4. read, write가 실패 할 시 IOException을 반환

File Download

@GetMapping("/file")
	public ResponseEntity<?> download(@RequestParam("file")String name, HttpServletResponse response{
		returnResponseEntity.ok(downloadFileService.getFile(name, response));
}
  1. 찾을 파일의 이름(또는 id)와 파일을 담아 보낼 response가 필요
  2. response.getOutputStream() 에 설정 한 buffer의 크기만큼 나눠서 데이터를 담아 보냄
  3. 다운로드가 실패 했을 때는 Exception을 반환 하는 것 보다 메시지를 반환해 다시 내려받을 수 있게 하는것이 좋지 않을까?

업로드 크기 제한

spring:
	servlet:
	    multipart:
	      maxFileSize: 10MB
	      maxRequestSize: 10MB
  • 기본적으로 10240Bytes이며 다룰 수 있는 최대 크기는 위와 같이 설정 가능하다

제한사항

  • 데이터베이스에 파일 전체를 저장 하는 것은 비효율적이라고 생각해 실제 파일의 저장공간과 정보를 담은 DB를 분리
    • DB에는 파일의 정보만 가지고 있는데 두 저장소 사이의 일관성은 어떻게 유지하는게 효율적일지
    • 매 요청마다 DB와 저장소의 일관성을 확인하는 작업은 cost가 클 것임

image-api-server브렌치로 이동