개발/Spring

Spring boot s3 이미지 Upload, url 이미지 다운로드하기

JangHC 2022. 3. 19. 15:12

소셜 로그인해서 프로필 사진을 s3에 업로드 하거나 이미지를 수정해서 s3에 올려야 하는 경우가 있었다.

 

s3Manager를 만들어서 모듈화 했다.

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
@Component
public class S3Manager {
		
    private final AmazonS3Client amazonS3Client;
    @Value("${cloud.aws.s3.bucket}")
    private String bucket;
     
    public String upload(MultipartFile multipartFile, String fileName) throws IOException {
        File uploadFile = convert(multipartFile)
                .orElseThrow(() -> new IllegalArgumentException("MultipartFile -> File로 전환이 실패했습니다."));
 
        return upload(uploadFile, fileName);
    }
 
    public String upload(File uploadFile, String fileName) {
        String uploadImageUrl = putS3(uploadFile, fileName);
        removeNewFile(uploadFile);
        return uploadImageUrl;
    }
 
    private String putS3(File uploadFile, String fileName) {
        amazonS3Client.putObject(new PutObjectRequest(bucket, fileName, uploadFile).withCannedAcl(CannedAccessControlList.PublicRead));
        return amazonS3Client.getUrl(bucket, fileName).toString();
    }
 
    private void removeNewFile(File targetFile) {
        if (targetFile.delete()) {
            log.info("파일이 삭제되었습니다.");
        } else {
            log.info("파일이 삭제되지 못했습니다.");
        }
    }
 
    private Optional<File> convert(MultipartFile file) throws IOException {
        File convertFile = new File(file.getOriginalFilename());
        System.out.println("convertFile = " + convertFile);
        if(convertFile.createNewFile()) {
            try (FileOutputStream fos = new FileOutputStream(convertFile)) {
                fos.write(file.getBytes());
            }
            return Optional.of(convertFile);
        }
        return Optional.empty();
    }
    
	public File downloadImage(String imageUrl,String fileName) {
		URL url;
		//읽기 객체
		InputStream is;
		//쓰기 객체
		OutputStream os;
		try {
			url = new URL(imageUrl);
			
			is = url.openStream();
			
			os = new FileOutputStream(fileName);
			
			byte[] buffer = new byte[1024*16];
			
			while (true) {
				int inputData = is.read(buffer);
				if(inputData == -1)break;
				os.write(buffer,0,inputData);
			}

			is.close();
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return new File(fileName);
	}
}

 

application.properties

 

# AWS Account Credentials (AWS 접근 키)
cloud.aws.credentials.access-key='' //a키
cloud.aws.credentials.secret-key='' //s키

# AWS S3 bucket Info (S3 버킷정보)
cloud.aws.s3.bucket='' // 버킷이름
cloud.aws.region.static=ap-northeast-2
cloud.aws.stack.auto=false

 

gradle

 

implementation 'org.springframework.cloud:spring-cloud-starter-aws-secrets-manager-config:2.2.6.RELEASE'