위로 아래

Multipart

  1. 웹 클라이언트가 요청을 보낼 때 http 프로토콜의 바디 부분에 데이터를 여러 부분으로 나눠서 보내는 것
  2. Multipart data : 
  3. 파일을 전송할 때 주로 사용한다.
  4. HttpServletRequest는 파일 업로드를 지원하지 않는다. 
  5. name이 달라야 한다.
  6. 사진과 파일 두 가지 타입의 데이터를 보낼 수 있도록 해준다.
  7. method는 POST만 가능하다

 

enctype 설정

form 태그에 enctype으로 multipart/form-data를 주어야 한다.

<form method="post" enctype="multipart/form-data">

	<input type="file" name="name">
    
</form>

 

파일 업로드 경로 설정

#파일 업로드 경로 설정
resources.location=D:/ljs/Ecom_Work_js/upload
resources.uri_path=/upload

 

 

컨트롤러에서 파일 받기

package com.ecom4.product.web;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.ecom4.common.dto.PageDTO;
import com.ecom4.custom.dto.MemberDTO;
import com.ecom4.product.dto.ProductDTO;
import com.ecom4.product.service.ProductService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@Controller
public class ProductController {

	@Autowired
	private ProductService productservice;
	
	//실제로 파일이 저장되는 파일 서버 경로를 가져온 것. properties에 있는 주소 불러와 스트링 변수 resourceLocation에 저장
	@Value("${resources.location}")
	String resourcesLocation;
	

	@RequestMapping ("/productMgtProc")
	public String productInForm(HttpServletRequest request, HttpServletResponse response,
			Model model, ProductDTO pdto, PageDTO pageDto, @RequestParam("image2") MultipartFile file) {
		
		
		...
    
	}
}

 

 

 

메소드

//파일 이름 가져오기
getOriginalFilename()

//부모 디렉토리를 File 객체로 생성 후 리턴
getParentFile()

//경로상에 없는 모든 디렉토리 생성
mkdirs()

//업로드
transferTo()

 

 

https://gunbin91.github.io/spring/2019/09/24/spring_12_multipart.html

 

스프링 MultiPart 파일처리

기존 JSP에서도 파일 업로드 처리를 할 수 있었지만, Spring에는 좀 더 쉽게 파일을 업로드할 수 있는 기능을 지원한다.

gunbin91.github.io