[SpringBoot] List<MultipartFile> 이용해서 파일 여러개 S3 저장하기

0

SpringBoot

목록 보기
2/3

Springboot에서 이미지 객체 AWS S3로 업로드 하기

앞의 포스팅에서는 front에서 이미지 1개를 받아서 
springboot를 통해서 aws s3객체에 업로드 하는 방법을 포스팅 하였습니다. 

이번 시간에는 사진을 여러개 한번에 받아서 S3객체에 올리는 방법을 포스팅 하도록 하겠습니다 !!!

Frontend

html

<!DOCTYPE html>
<html>
<head>
  <title>Profile Image Upload</title>
</head>
<body>
  <h1>Profile Image Upload</h1>
  <input type="file" id="fileInput" multiple />
  <button onclick="uploadImages()">Upload Images</button>

  <script>
    function uploadImages() {
      const fileInput = document.getElementById('fileInput');
      const formData = new FormData();

      for (const file of fileInput.files) {
        formData.append('images', file);
      }

      fetch('http://localhost:8080/user/file/active', {
        method: 'POST',
        body: formData,
      })
      .then(response => response.json())
      .then(data => {
        console.log(data);
        alert('Images uploaded successfully!');
      })
      .catch(error => {
        console.error('Error:', error);
        alert('Failed to upload images.');
      });
    }
  </script>
</body>
</html>

input 태그 안에 multiple을 적어주면 사진을 여러장 선택 할 수 있게 됩니다.

그리고 이미지를 업로드 하게 되면 SpringBoot와 api 통신될 수 있게 설정 해보겠습니다.

Controller

    @PostMapping("file/active")
    public List<String> uploadActiveImages(@RequestParam("images") List<MultipartFile> multipartFiles) throws IOException {
        return userService.uploadActiceImages(multipartFiles);
    }

이번엔 전 내용과 다르게 List로 MultipartFile을 사용해서 List 객체로 받아줍니다.

Service

    @Override
    public List<String> uploadActiceImages(List<MultipartFile> MultipartFile) throws IOException {
        List<String> urlList = s3Uploader.upload(MultipartFile, "static/active");
        for (int i=0; i< urlList.size(); i++) {
            System.out.println(urlList);
        }
        return urlList;
    }

List(MultipartFile) 객체를 S3upload 객체로 넘긴다음 받아온 url을 출력시켜 줍니다.

테스트

html파일에 사진을 여러장 클릭하고, upload 버튼을 눌러줍니다.

springboot

s3

이렇게 테스트를 마치고 뿌듯함을 만끽하면서 github에 올렸습니당 ㅎㅎ

profile
고민이 많은 개발자

0개의 댓글