또두
꾸준함을 기록
또두
전체 방문자
오늘
어제
  • 분류 전체보기 (12)
    • 42Seoul (1)
    • CS (1)
    • Nest.js (0)
    • Database (2)
      • Postgresql (2)
      • MySQL | MariaDB (0)
    • Server (5)
    • Shell script (0)
    • C (1)
    • Spring (1)
    • etc (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • AWS
  • IOC
  • di
  • File
  • certbot
  • ACM
  • case-sensitive
  • github
  • chrome
  • EC2
  • multipart
  • Redirection
  • virtualization
  • nestjs
  • stdout
  • garbia
  • nginx
  • PostgreSQL
  • Session
  • domain
  • remote-ssh
  • stderr
  • 42seoul
  • Pipe
  • vscode
  • ssh
  • Google Apps Script
  • OOP
  • Write
  • SSL

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
또두

꾸준함을 기록

Spring

이미지 받기

2023. 6. 6. 21:54

아래 코드와 같이 @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;
    }
}
    또두
    또두

    티스토리툴바