본문 바로가기
IT/AWS

AWS S3 이미지 업로드

by 봉즙 2020. 2. 3.

AWS S3에서 버킷을 만들어 준 후, 자격증명에서 I AM을 통해 엑세스 키를 만들어 준 후 시작한다.

package com.football.fcbayern.util;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

public class AwsS3Util {
    private static final String accessKey = "엑세스키";//git에 올리면 aws에서 연락옴..
    private static final String secretKey = "시크릿키";

    private AmazonS3 amazonS3;

    public AwsS3Util() {
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTP);
        this.amazonS3 = new AmazonS3Client(awsCredentials, clientConfiguration) {
        };
        amazonS3.setEndpoint("s3.ap-northeast-2.amazonaws.com");
    }

    public List<Bucket> getBucketList() {
        return amazonS3.listBuckets();
    }

    public Bucket createBucket(String bucketName) {
        return amazonS3.createBucket(bucketName);
    }

    public void createFolder(String bucketName, String folderName) {
        amazonS3.putObject(bucketName, folderName + "/", new ByteArrayInputStream(new byte[0]), new ObjectMetadata());
    }

    public void fileUpload(String bucketName, String fileName, byte[] fileData) throws FileNotFoundException {
        String filePath = (fileName).replace(File.separatorChar, '/');// 파일 구분자를 '/'으로 설정
        ObjectMetadata objectMetadata = new ObjectMetadata();

        objectMetadata.setContentLength(fileData.length); //메타데이터 설정 128kb -> 파일 크기만큼으로 변경
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileData);

        amazonS3.putObject(bucketName, filePath, byteArrayInputStream, objectMetadata);
    }

    public void fileDelete(String bucketName, String fileName) {
        String imgName = (fileName).replace(File.separatorChar, '/');
        amazonS3.deleteObject(bucketName, imgName);
        System.out.println("삭제 성공");
    }

    public String getFileURL(String bucketName, String fileName) {
        System.out.println("파일 명 : " + fileName);
        String imgName = (fileName).replace(File.separatorChar, '/');
        return amazonS3.generatePresignedUrl(new GeneratePresignedUrlRequest(bucketName, imgName)).toString();
    }

}
package com.football.fcbayern.util;

import java.io.File;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.UUID;

public class UploadFileUtils {

    public static String uploadFile(String uploadPath, String originalName, byte[] bytes) throws Exception{

        AwsS3Util awsS3Util = new AwsS3Util();
        final String bucketName = "woolution";

        UUID uuid = UUID.randomUUID();

        String saveName = "/"+uuid.toString()+"_"+originalName;

        String savedPath = calendarPath(uploadPath);

        String uploadedFileName = (savedPath+ saveName).replace(File.separatorChar,'/');
        //AwsS3Util fileUpload 메서드를 사용해 업로드
        awsS3Util.fileUpload(bucketName, uploadPath+uploadedFileName, bytes);

        return uploadedFileName;
    }

    private static String calendarPath(String uploadPath){

        Calendar calendar = Calendar.getInstance();

        String yearPath = File.separator + calendar.get(Calendar.YEAR);

        String monthPath = yearPath + File.separator + new DecimalFormat("00").format(calendar.get(Calendar.MONTH) + 1);

        String datePath = monthPath + File.separator + new DecimalFormat("00").format(calendar.get(Calendar.DATE));

        mkdir(uploadPath, yearPath, monthPath, datePath);

        return datePath;
    }

    private static void mkdir(String uploadPath, String... paths ){ //... 동일한 파라미터 여러개 받을 경우 자동으로 배열 처리

        if (new File(paths[paths.length - 1]).exists()) {
            return;
        }

        for (String s: paths){
            File dirPath = new File(uploadPath + s);

            if(!dirPath.exists()){
                dirPath.mkdir();
            }
        }
    }
}
package com.football.fcbayern.controller;

import com.amazonaws.util.IOUtils;
import com.football.fcbayern.model.ProfileAttachModel;
import com.football.fcbayern.service.ProfileAttachService;
import com.football.fcbayern.service.ProfileService;
import com.football.fcbayern.util.AwsS3Util;
import com.football.fcbayern.util.UploadFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

@RequestMapping("/profileAttach")
@RestController
public class ProfileAttachController {

    private ProfileAttachService profileAttachService;
    private AwsS3Util awsS3Util = new AwsS3Util();
    private final static String bucketName = "woolution";

    @Autowired
    public void setProfileAttachService(ProfileAttachService profileAttachService) {
        this.profileAttachService = profileAttachService;
    }

    @PostMapping(value = "/insertAttachInfo", consumes = "application/json", produces = {MediaType.TEXT_PLAIN_VALUE})
    public ResponseEntity<String> insertInfo(@RequestBody ProfileAttachModel profileAttachModel) {
        int count = profileAttachService.insert(profileAttachModel);
        return count == 1 ? new ResponseEntity<>("success", HttpStatus.OK) : new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @PostMapping(value = "/insertImg", produces = "text/plain;charset=UTF-8")
    public String uploadAjaxCertificate(MultipartFile uploadFile) throws Exception {

        String uploadPath = "profileAttach";

        ResponseEntity<String> img_path = new ResponseEntity<>(
                UploadFileUtils.uploadFile(uploadPath, uploadFile.getOriginalFilename(), uploadFile.getBytes()),
                HttpStatus.CREATED);

        return img_path.getBody();
    }

    @GetMapping(value = "/getAttachList", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<ProfileAttachModel>> getAttachList(){
        System.out.println(profileAttachService.getAttachList());
        return new ResponseEntity<>(profileAttachService.getAttachList(), HttpStatus.OK);
    }

    @GetMapping("/getImg")
    public ResponseEntity<byte[]> getImg(String fileName, String directory) throws Exception {
        System.out.println(directory);

        InputStream inputStream = null;
        ResponseEntity<byte[]> responseEntity = null;
        HttpURLConnection httpURLConnection = null;
        System.out.println(fileName);

        String inputDirectory = null;
        inputDirectory = directory;
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            URL url;
            try {
                url = new URL(awsS3Util.getFileURL(bucketName, inputDirectory + fileName));
                httpURLConnection = (HttpURLConnection) url.openConnection();
                inputStream = httpURLConnection.getInputStream();
            } catch (Exception e) {
//              url = new URL(awsS3Util.getFileURL(bucketName, inputDirectory + fileName));
//              httpURLConnection = (HttpURLConnection)url.openConnection();
//              inputStream =  httpURLConnection.getInputStream();
                e.printStackTrace();
            }
            responseEntity = new ResponseEntity<byte[]>(IOUtils.toByteArray(inputStream), httpHeaders, HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            responseEntity = new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
        } finally {
            assert inputStream != null;
            inputStream.close();
        }
        return responseEntity;
    }

}

 

$('#profileReg').click(function () {
    // $(".content").load("/team?lang=" + getCookie('APPLICATION_LOCALE'));
    $(".content").load("/profileReg");
});

function profileInfoList() {
    return new Promise((resolve) => {
        $.ajax({
            url: '/profile/infoList',
            type: 'GET',
            success: (result) => {
                resolve(result);
            }
        })
    })
}

$.ajax({
    type: 'GET',
    url: '/profile/category',
    dataType: "JSON",
    success: ((data) => {
        profileInfoList().then(
            function profileInfoList(result) {

                $.ajax({
                    url: '/profileAttach/getAttachList',
                    type: 'GET',
                    success: (attachData) => {

                        let str = "";
                        for (let i = 0; i < data.length; i++) {
                            const profileFilter = result.filter((element) => {
                                return element.profileCategoryNo === data[i].profileCategoryNo;
                            });
                            //반복문 통해 카테고리 멸로 필터링

                            for (let j = 0, list = profileFilter.length || 0; j < list; j++) {
                                const attachFilter = attachData.filter((element) => {
                                    return element.profileNo === profileFilter[j].profileNo;
                                });
                                //id fk 로 filter처리를 해서 하나만 남겨 배열 0을 통해 첨부파일 정보 획득

                                str = "<div class='container-custom'>\n" +
                                    "            <h1 class='bold profile-category'>" + data[i].categoryNm + "</h1>\n" +
                                    "            <div class='col-lg-12'>\n" +
                                    "                <div class='row'>\n" +
                                    "                    <div class='col-lg-3'>\n" +
                                    "                        <div class='profile-img text-center'>\n" +
                                    "                            <img src='/profileAttach/getImg?fileName=" + attachFilter[0].uuid + "&directory=" + attachData[0].uploadPath + "' alt=''>\n" +
                                    "                            <div>\n" +
                                    "                                <span class='text-primary'>" + profileFilter[j].profileNm + "</span></div>\n" +
                                    "                            <div>\n" +
                                    "                                <span>" + profileFilter[j].birthDate + "</span>\n" +
                                    "                            </div>\n" +
                                    "                        </div>\n" +
                                    "                    </div>\n" +
                                    "                </div>\n" +
                                    "            </div>\n" +
                                    "        </div>"
                            }
                        }
                    // <%--<img class="img-fluid"	src="/profile/getImg?fileName=66299ae7-1409-4048-81e9-77365de0e549_Neuer.webp&directory=profileAttach/2020/01/23/">--%>

                        $("#profileList").html(str);
                    }
                });
            }
        )
    })
});

'IT > AWS' 카테고리의 다른 글

AWS EC2 – mariadb 설치  (0) 2019.11.26

댓글