[스프링 MVC 2편 - 백엔드 웹 개발 활용 기술] 11. 파일 업로드

Turtle·2024년 8월 5일
0
post-thumbnail

🙄파일 업로드 소개

파일을 업로드하려면 파일은 문자가 아니라 바이너리 데이터를 전송해야 한다. 문자를 전송하는 방식으로는 파일을 전송하기 어렵다. 폼을 전송할 때 파일만 전송하는 것이 아니라 첨부파일이나 문자 데이터를 같이 전송해야 하는 경우 HTTP의 multipart/form-data를 사용해야 한다.

  • 문자를 전달하는 경우 : Content-Type: application/x-www-form-urlencoded
  • 파일을 전달하는 경우 : Content-Type: multipart/form-data

🙄서블릿과 파일 업로드

🗃️서블릿이 제공하는 Part를 사용한 예제 코드

  • part.getSubmittedFileName() : 클라이언트가 전달한 파일명
  • part.getInputStream() : 전송 데이터를 읽어오기
  • part.write(...) : 전송된 데이터를 저장하기
package hello.upload.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.Part;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collection;

@Slf4j
@Controller
@RequestMapping("/servlet/v2")
public class ServletUploadControllerV2 {

	// application.properties에 설정한 옵션을 사용
	@Value("${file.dir}")
	private String fileDir;

	@GetMapping("/upload")
	public String newFile() {
		return "upload-form";
	}

	@PostMapping("/upload")
	public String saveFileV2(HttpServletRequest request) throws ServletException, IOException {
		log.info("request={}", request);

		String itemName = request.getParameter("itemName");
		log.info("itemName={}", itemName);

		Collection<Part> parts = request.getParts();
		log.info("parts={}", parts);

		for (Part part : parts) {
			log.info("==== PART ====");
			log.info("name={}", part.getName());
			Collection<String> headerNames = part.getHeaderNames();
			for (String headerName : headerNames) {
				log.info("header {} : {}", headerName, part.getHeader(headerName));
			}

			// 클라이언트가 전달한 파일명
			log.info("submittedFileName={}", part.getSubmittedFileName());
			log.info("size={}", part.getSize());

			// Part의 전송 데이터 읽기
			InputStream inputStream = part.getInputStream();
			String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
			log.info("body={}", body);

			// Part를 통해 전송된 데이터를 저장
			// 클라이언트가 전달한 파일명이 존재한다면?
			if (StringUtils.hasText(part.getSubmittedFileName())) {
				String fullPath = fileDir + part.getSubmittedFileName();
				log.info("파일 저장 경로 fullPath={}", fullPath);
				part.write(fullPath);
			}
		}
		return "upload-form";
	}
}

🙄스프링과 파일 업로드

🗃️스프링이 제공하는 MultipartFile를 사용한 예제 코드

  • file.getSubmittedFileName() : 업로드할 파일명
  • file.transferTo() : 파일 저장
package hello.upload.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@Controller
@RequestMapping("/spring")
public class SpringUploadController {

	// application.properties에 설정한 옵션을 사용
	@Value("${file.dir}")
	private String fileDir;

	@GetMapping("/upload")
	public String newFile() {
		return "upload-form";
	}

	@PostMapping("/upload")
	public String saveFileV2(@RequestParam(name = "itemName") String itemName,
							 @RequestParam(name = "file") MultipartFile file,
							 HttpServletRequest request) throws IOException {
		log.info("request={}", request);
		log.info("itemName={}", itemName);
		log.info("multiPartFile={}", file);

		// 파일이 비어있지 않다면?
		if (!file.isEmpty()) {
			// 업로드 파일명 : getOriginalFilename()
			String fullPath = fileDir + file.getOriginalFilename();
			log.info("파일 저장 경로 fullPath={}", fullPath);
			// 파일 저장 : transferTo()
			file.transferTo(new File(fullPath));
		}
		return "upload-form";
	}
}

🙄예제로 구현하는 파일 업로드(핵심)

🗃️UploadFile

  • 업로드한 파일명(uploadFileName)과 서버에 저장할 파일명(storeFileName) 두 개를 만든다.
  • 이 때, 서로 다른 고객이 같은 이름의 파일을 업로드하여 서버에 그대로 저장이 되면 중복이 되어 다른 파일로 덮어씌여지는 문제가 발생한다. 이를 방지하기 위해 서버에 저장할 때 UUID를 사용하여 중복되지않도록 한다.
@Getter
@Setter
@AllArgsConstructor
public class UploadFile {
	private String uploadFileName; // 업로드한 파일명
	private String storeFileName;  // 서버에 저장할 파일명
}
@Component
public class FileStore {

	@Value("${file.dir}")
	private String fileDir;

	public String getFullPath(String fileName) {
		// C:/Users/TOP/ + ...
		return fileDir + fileName;
	}

	// 복수 파일
	public List<UploadFile> storeFiles(List<MultipartFile> multipartFiles) throws IOException {
		List<UploadFile> storeFileResult = new ArrayList<>();
		for (MultipartFile multipartFile : multipartFiles) {
			if (!multipartFile.isEmpty()) {
				storeFileResult.add(storeFile(multipartFile));
			}
		}
		return storeFileResult;
	}


	// 단일 파일
	public UploadFile storeFile(MultipartFile multipartFile) throws IOException 	{
		if (multipartFile.isEmpty()) {
			return null;
		}
		String originalFilename = multipartFile.getOriginalFilename();

		// 확장자 확인
		int i = originalFilename.lastIndexOf(".");
		String ext = originalFilename.substring(i + 1);

		// 서로 다른 고객이 같은 이름의 이미지를 업로드 시 덮어씌여지는 문제가 발생
		// 이를 해결하기 위해 UUID 값을 활용
		String uuid = UUID.randomUUID().toString();

		// 서버에 저장하는 파일명
		String storeFileName = uuid + "." + ext;
		multipartFile.transferTo(new File(getFullPath(storeFileName)));
		return new UploadFile(originalFilename, storeFileName);
	}
}
@Slf4j
@Controller
public class ItemController {

	private final ItemRepository itemRepository;
	private final FileStore fileStore;

	@Autowired
	public ItemController(ItemRepository itemRepository, FileStore fileStore) {
		this.itemRepository = itemRepository;
		this.fileStore = fileStore;
	}

	@GetMapping("/items/new")
	public String itemForm(@ModelAttribute(name = "form") ItemForm form) {
		return "item-form";
	}

	@PostMapping("/items/new")
	public String itemSave(@ModelAttribute(name = "form") ItemForm form, RedirectAttributes redirectAttributes) throws IOException {
		UploadFile attachFile = fileStore.storeFile(form.getAttachFile());
		List<UploadFile> storeImageFiles = fileStore.storeFiles(form.getImageFiles());

		Item item = Item.builder()
						.id(form.getItemId())
						.itemName(form.getItemName())
						.attachFile(attachFile)
						.imageFiles(storeImageFiles)
						.build();
		itemRepository.save(item);
		redirectAttributes.addAttribute("itemId", item.getId());
		return "redirect:/items/{itemId}";
	}

	// 저장된 파일을 고객에게 보여주는 매핑
	@GetMapping("/items/{id}")
	public String items(@PathVariable(name = "id") Long id, Model model) {
		Item findItem = itemRepository.findById(id);
		model.addAttribute("item", findItem);
		return "item-view";
	}

	// java.net.MalformedURLException: unknown protocol: c (오류)
	@ResponseBody
	@GetMapping("/images/{fileName}")
	public Resource downloadImageV1(@PathVariable(name = "fileName") String fileName) throws MalformedURLException {
		// UrlResource wraps a java.net.URL and can be used to access any object that is normally accessible with a URL, such as files, an HTTPS target, an FTP target, and others.
		// All URLs have a standardized String representation, such that appropriate standardized prefixes are used to indicate one URL type from another.
		// This includes file: for accessing filesystem paths, https: for accessing resources through the HTTPS protocol, ftp: for accessing resources through FTP, and others.
		return new UrlResource("file:" + fileStore.getFullPath(fileName));
	}

	// 첨부 파일 클릭하여 다운로드
	@GetMapping("/attach/{itemId}")
	public ResponseEntity<Resource> downloadImageV2(@PathVariable(name = "itemId") Long itemId) throws MalformedURLException {
		Item item = itemRepository.findById(itemId);
		String storeFileName = item.getAttachFile().getStoreFileName();
		String uploadFileName = item.getAttachFile().getUploadFileName();
		UrlResource urlResource = new UrlResource("file:" + fileStore.getFullPath(storeFileName));

		// 인코딩
		String encodedUploadFileName = UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);

		// header : Content-Disposition
		String contentDisposition = "attachment; filename=\"" + encodedUploadFileName + "\"";
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
				.body(urlResource);
	}
}

0개의 댓글