jnk1m
Foliage IT
jnk1m
전체 방문자
오늘
어제
  • 분류 전체보기 (209)
    • Today I Learned (34)
    • Java (47)
    • Database (15)
    • [NHN Academy] (27)
    • Spring (47)
    • HTML + CSS + JavaScript (11)
    • JSP (3)
    • Node.js (10)
    • React Native (2)
    • 기타 (8)
    • 스크랩 (5)

인기 글

최근 글

티스토리

hELLO · Designed By 정상우.
글쓰기 / 관리자
jnk1m

Foliage IT

Today I Learned

[TIL] 23/8/22 AWS S3 설정, 이미지 업로드 코드

2023. 9. 14. 23:56

1. pom.xml에 dependency 추가

<dependency>
	<groupId>com.amazonaws</groupId>
	<artifactId>aws-java-sdk-s3</artifactId>
	<version>1.12.470</version>
</dependency>

2. application.properties 설정

#S3
aws.accessKeyId=액세스키아이디
aws.secretKey=시크릿키
aws.region=리전
aws.s3.bucket = 버킷이름

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB

 

3. s3 config

@Configuration
public class S3Config {
  @Value("${aws.accessKeyId}")
  private String accessKeyId;

  @Value("${aws.secretKey}")
  private String secretKey;

  @Value("${aws.region}")
  private String region;

  @Bean
  public AmazonS3Client amazonS3Client() {
    BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKeyId, secretKey);
    return (AmazonS3Client) AmazonS3ClientBuilder.standard()
            .withRegion(region)
            .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials))
            .build();
  }
}

 

4. controller

  @PostMapping("/menu/{menuId}/image")
  public String setMenuImage(@PathVariable("menuId") int menuId,
                             @RequestParam("imageFile") MultipartFile file) throws IOException {
    long maxFileSize = 100 * 1024;
    if (file.getSize() > maxFileSize) {
      throw new FileSizeLimitExceededException("File size must be less than 100KB.", file.getSize(), maxFileSize);
    }
    String menuCategoryName = menuService.getMenuCategoryName(menuId).toLowerCase();
    String folderPath = menuCategoryName + "/";

    String fileName = folderPath + Objects.requireNonNull(file.getOriginalFilename()).trim().toLowerCase().replaceAll("\\s", "-");

    File tempFile = convertMultiPartToFile(file);


    PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, tempFile);
    s3.putObject(putObjectRequest);

    tempFile.delete();

    String imgUrl = s3.getUrl(bucket, fileName).toString();

    menuService.setMenuImage(menuId, imgUrl);

    return "redirect:/admin/menu/" + menuId;
  }

  private File convertMultiPartToFile(MultipartFile file) throws IOException {
    File convFile = File.createTempFile("temp", null);
    try (FileOutputStream fos = new FileOutputStream(convFile)) {
      fos.write(file.getBytes());
    }
    return convFile;
  }

 

4. image-upload.html

        <div class="container mt-4">
            <h1>Upload Image</h1>
            <div class="col-md-4">
                <div th:if="${menuImgPath != null}">
                    <a href="#" onclick="openImagePopup(); return false;">
                        <img th:src="${menuImgPath}" alt="Menu Image" class="img-fluid"/>
                    </a>
                </div>
                <div th:if="${menuImgPath == null}">
                    <p>No Image Available.</p>
                </div>
            </div>


            <form id="fileUploadForm" th:action="@{/admin/menu/{menuId}/image(menuId = ${menuId})}" method="post" enctype="multipart/form-data">
                <div class="form-group p-2">
                    <label for="imageFile"><strong>Image:</strong></label>
                    <input type="file" class="form-control-file" id="imageFile" name="imageFile" accept="image/*"/>
                    <span>
                    <p class="image-description"> Please visit
                        <a href="https://imagecompressor.com" target="_blank">the linked website</a>
                        to optimize your image before uploading it for website optimization.</p>
                    <p class="image-description">1. Only English file names are allowed for images. 2. Images are optimized at a size of 750 x 563. </p>
                    </span>
                </div>
                <button type="submit" class="btn btn-primary">Save</button>
            </form>
        </div>

 

5. 이미지 파일 사이즈 js 검증 

<script>
    function openImagePopup() {
        var imageUrl = document.querySelector('.img-fluid').getAttribute('src');
        window.open(imageUrl, 'Image Popup', 'width=100%,height=100%');
    }

    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('fileUploadForm').addEventListener('submit', function (e) {
            var fileInput = document.getElementById('imageFile');
            var file = fileInput.files[0];
            var maxFileSize = 100 * 1024;

            if (file && file.size > maxFileSize) {
                alert('File size must be less than 100KB.');
                e.preventDefault();
            }
        });
    });


</script>
    'Today I Learned' 카테고리의 다른 글
    • [TIL] 23/9/22 Google OAuth Sign in authorization_request_not_found 에러 (로드밸런서 스티키 세션 설정 자세히)
    • [TIL] 23/9/13 메뉴 디테일 수정하기 구현
    • [TIL] 23/8/18 Category 테이블 View 추가 + 뷰 생성법, 사용법, Spring boot entity 작성
    • [TIL]23/8/2 고객용 주문 번호 생성, 유효성 검사, 시간대 포맷팅, 정규표현식

    티스토리툴바