'fileupload'에 해당되는 글 2건

 

2022.02.24 - [[Spring]/springboot] - [SpringBoot] RestAPI 파일업로드 - 1

 

[SpringBoot] RestAPI 파일업로드 - 1

1. start.spring.io에서 스프링 프로젝트 생성하기 2. 파일 업로드 관련 properties 생성 spring: servlet: multipart: max-request-size: 500MB # request 요청 제한(defalut 10mb) max-file-size: 500MB # 파..

minaminaworld.tistory.com


1. 프로젝트 메인에서 업로드 폴더 생성 

   @Value("${uploadFolder}")
    private String uploadFolder;

    public static void main(String[] args) {
        SpringApplication.run(TistoryFileDownloadApplication.class, args);
    }

    @PostConstruct
    public void createUploadFolder() {
        Path upload = Paths.get(uploadFolder);
        try {
            if (!Files.exists(upload)) {
                Files.createDirectory(upload);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2. 파일 저장 서비스 코드 작성

@Service
public class FileService {

    @Value("${uploadFolder}")
    private String uploadFolder;

    public void save(MultipartFile file) {
        Path upload = Paths.get(uploadFolder);
        try {
            Files.copy(file.getInputStream(), upload.resolve(file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. Postman 테스트 결과 

 

블로그 이미지

미나미나미

,

1. start.spring.io에서 스프링 프로젝트 생성하기


 

2. 파일 업로드 관련 properties 생성

spring:
  servlet:
    multipart:
      max-request-size: 500MB # request 요청 제한(defalut 10mb)
      max-file-size: 500MB # 파일 크기 업로드 데한 (defalut 10mb)

uploadFoloder: upload

3. 파일 RestController 생성 

@PostMapping("/upload")
public ResponseEntity upload(
	@RequestParam("files") MultipartFile[] files // 파일 받기
) {
	// 1. response 객체 생성
    HashMap<String, Object> resultMap = new HashMap<>();
    HashMap<String, Object> responseData = new HashMap<>();
    
    // 2. 받은 파일 데이터 확인
    List<HashMap<String, Object>> fileNames = new ArrayList<>();
    	Arrays.stream(files).forEach(f -> {
    	HashMap<String, Object> map = new HashMap<>();
	    System.out.println("f.getOriginalFilename() = " + f.getOriginalFilename());
    	map.put("fileName", f.getOriginalFilename());
    	map.put("fileSize", f.getSize());
    
        fileNames.add(map);
    });
    
    // 3. response 하기
    responseData.put("files", fileNames);
    resultMap.put("response", responseData);
    return ResponseEntity.ok().body(resultMap);
}

4. Postman으로 테스트 하기  

   파일을 서버에서 전달 테스트

블로그 이미지

미나미나미

,