예지의 개발 로그포스 (Yeji's Log Force)

[Spring] File Upload 1 - 개념정리 (MultipartResolver) 본문

Spring

[Spring] File Upload 1 - 개념정리 (MultipartResolver)

Yeji Heo 2024. 3. 30. 11:39

클라이언트에서 서버로 이미지 파일을 업로드해보면서 공부한

Content-Type, Multipart, Spring파일 업로드 등 내용을 정리한다.

+ SpringBoot를 사용하지는 않았다.


 

1. Content-Type

 

HTTP에서 request를 보낼 때

HTTP통신에 필요한 정보(url, Header, Body 등)을 세팅했었다. 

//Apache의 HTTPComponent를 이용해 HTTPRequest를 만들어 보내고, Response받아보는 Test

public static void getUserTest_Codehaus() throws Exception{
		
		// HttpClient : Http Protocol 의 client 추상화 
		HttpClient httpClient = new DefaultHttpClient();
		
		String url= 	"http://localhost:8080/user/json/getUser/admin";

		// HttpGet : Http Protocol 의 GET 방식 Request
		HttpGet httpGet = new HttpGet(url);
		httpGet.setHeader("Accept", "application/json");
		httpGet.setHeader("Content-Type", "application/json");
		
		// HttpResponse : Http Protocol 응답 Message 추상화
		HttpResponse httpResponse = httpClient.execute(httpGet);
		
		//==> Response 확인
		System.out.println(httpResponse);
		System.out.println();

		//==> Response 중 entity(DATA) 확인
		HttpEntity httpEntity = httpResponse.getEntity();
		
		//==> InputStream 생성
		InputStream is = httpEntity.getContent();
		BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
		
		//==> API 확인 : Stream 객체를 직접 전달 
		JSONObject jsonobj = (JSONObject)JSONValue.parse(br);
		System.out.println(jsonobj);
	
		ObjectMapper objectMapper = new ObjectMapper();
		 User user = objectMapper.readValue(jsonobj.toString(), User.class);
		 System.out.println(user);
	}

 

위 코드에서 httpGet.setHeader()를 통해 Header를 만들어 보냈는데

Content-Type을 Application타입의 JSON 으로 지정해준 경험이 있다. 

서버는 Content-Type을 통해 Request의 콘텐츠의 타입을 이해하고, 파싱하여 사용하는 것이다.

 

가령, 서버쪽에서 @RequestBody 등을 사용하여 JSON데이터를 받겠다고 했다면

클라이언트에서는 Content-Type을 application/json타입으로 해야하는 것이다.

(그렇지 않으면 Unsupported Media Type 에러인 415 Http Status Code가 뜬다.)

 

 


 

2. Multipart Type 

 

Content-Type 은 Text타입, Application타입, Audio타입, MultiPart타입 등 여러 종류가 있다.

그 중 Multipart타입은 하나의 Body에 서로 다른 종류의 여러 데이터를 결합해 보낸다고한다.

 

RFC1341(MIME) : 7 The Multipart content type

7.2 The Multipart Content-Type In the case of multiple part messages, in which one or more different sets of data are combined in a single body, a "multipart" Content-Type field must appear in the entity's header. The body must then contain one or more "bo

www.w3.org

 

그 중 multipart/form-data는 File, ASCII가 아닌 Data, Binary Data 등을 Form submit으로 보내기 좋다고 한다.

Default encoding인 application/x-www-form-urlencoded타입은 Large quantities of binary data나 Text containing non-ASCII characters를 보내는데 적합하지 않기 때문이다.

 

Forms in HTML documents

17.1 Introduction to forms An HTML form is a section of a document containing normal content, markup, special elements called controls (checkboxes, radio buttons, menus, etc.), and labels on those controls. Users generally "complete" a form by modifying it

www.w3.org

 


 

3-1 . Spring MultipartResolver

 

  •  What is MultipartResolver

Multipart타입의 파일을 업로드 하기위한 strategy interface이다.

+ RFC1867규격(Form-based File Upload in HTML)을 따른다고 한다.

이 인터페이스의 구현체들은 application context(WAS개념을 말하는 듯 하다)에서 사용 될 수도 있고

standalone하게 사용 될 수도 있다고 한다.

 

  • How to use

DispatcherServlet에서는 default resolver가 없기 때문에

Multipart타입의 requests를 파싱할 MultipartResolver 구현체 Bean을

DispatcherServlet의 application context에 등록해줘야 한다.

그러면 DispatcherServlet(단일인입점)을 통해 request되는 모든 request들에 이 Resolver를 적용할 수 있게 되는 것이다.

+ Spring에서는 구현체로 StandardServletMultipartResolver 를 제공하고있다. CommonsMultipartResolver는 사라졌다고 한다.

 

  • How it works

MultipartResolver가 적용된 Request들은 HttpServletRequest로 Wrapping된다고 한다. 

그러면 컨트롤러들은 받은 Request를 비로소 MultipartFiles로서 cast하여 처리할 수 있다.

+ DispatcherServlet에 MultipartResolver를 쓰고싶지 않다면, 대안으로 MultipartFilter를 쓸 수도 있다.

이는 Spring의 web MVC Framework를 사용하지 않는 application에서 주로 사용된다고 한다.

 

MultipartResolver (Spring Framework 6.1.5 API)

Determine if the given request contains multipart content. Will typically check for content type "multipart/form-data", but the actually accepted requests might depend on the capabilities of the resolver implementation.

docs.spring.io

 


 

3-2 . Spring MultipartFile

 

Multipart타입 Request로부터 받은 uploaded file을 추상화, 캡슐화한 인터페이스이다.

즉, Name이나 Size 등 파일 정보를 가지고 있으므로

이 타입으로 Request Data를 받아주면 메서드들을 통해, 파일 활용이 가능한 것이다.

 

 

MultipartFile (Spring Framework 6.1.5 API)

getContentType Return the content type of the file. Returns: the content type, or null if not defined (or no file has been chosen in the multipart form)

docs.spring.io

 

다음 글에서 계속...(구현)
 

[Spring] File Upload 2 - 구현

[Spring] File Upload 1 - 개념정리 (MultipartResolver) 클라이언트에서 서버로 이미지 파일을 업로드해보면서 공부한 Content-Type, Multipart, Spring파일 업로드 등 내용을 정리한다. + SpringBoot를 사용하지는 않았

crayeji.tistory.com

 

'Spring' 카테고리의 다른 글

[Spring] File Upload 2 - 구현  (0) 2024.03.30
Comments