아래 코드와 같이 @RequestPart 어노테이션을 이용해 이미지를 받아올 수 있다.
value엔 이미지를 보낼 때 사용한 키 값을 넣으면 된다.
package com.example.demo.controller;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@RestController
@RequestMapping("/image")
@RequiredArgsConstructor
@Slf4j
public class ImageController {
@PostMapping("/upload")
public boolean getImage(@RequestPart(value = "file") MultipartFile reqFile) {
try {
log.info(reqFile.getName());
log.info(reqFile.getContentType());
File file = new File("path/project/src/main/resources/static/" + reqFile.getOriginalFilename() + ".jpg");
reqFile.transferTo(file);
} catch (Exception e) {
log.error(e.toString());
return false;
}
return true;
}
}
여러 이미지를 받으려면 아래와 같이 작성하면 된다.
@RequestPart 어노테이션은 똑같이 사용하면 된다.
주의할 점은 이미지를 전송할 때 모두 같은 키 값으로 보내야 한다.
또한 받을 때의 타입을 MultipartFile을 List로 여러개를 받을 수 있어야 한다.
package com.example.demo.controller;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.List;
@RestController
@RequestMapping("/image")
@RequiredArgsConstructor
@Slf4j
public class ImageController {
@PostMapping("/upload")
public boolean getImage(@RequestPart(value = "file") List<MultipartFile> reqFile) {
try {
for (MultipartFile partFile : reqFile) {
log.info(partFile.getName());
log.info(partFile.getContentType());
File file = new File("path/project/src/main/resources/static/" + partFile.getOriginalFilename() + ".jpg");
partFile.transferTo(file);
}
} catch (Exception e) {
log.error(e.toString());
return false;
}
return true;
}
}