hyeonga_code

Project_AWS_S3_서버에 이미지 업로드 프로젝트에 적용하기 ver.3 본문

Project_WEATHERWEAR

Project_AWS_S3_서버에 이미지 업로드 프로젝트에 적용하기 ver.3

hyeonga 2024. 1. 4. 07:59
반응형

시도 3. input 태그 하나에 여러 이미지 파일 한번에 업로드하기 > 컴퓨터에 저장하지 않고 바로 업로드

    - 파일 추가시 리스트로 파일 이름 정렬하고 이미지 미리보기 생성

 

FileController 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.w2.file;
 
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
 
@Controller
public class FileController {
    @Autowired
    private AwsS3 awsS3 = AwsS3.getInstance();
    
    @Autowired
    private FileService fileService;
    
    // 이미지 업로드 페이지 요청(테스트)
    @RequestMapping("/insertImage.do")
    public String insertCmImage() {
        System.out.println("[ FileController ] : insertCmImage/get");
        
        return "/test/insert_image2";
    }
 
    // 이미지 업로드 요청
    @PostMapping("/insertImage.do")
    public void insertCmImage(MultipartHttpServletRequest request , Model model) 
throws IOException {
        System.out.println("[ Controller ] : insertCmImage/post");
        
        // 업로드할 파일 기본 저장 위치
        String rootUploadDir = "C:" + File.separator + "Weatherwear";
        
        // 업로드할 파일 저장 위치        
        String uploadDir = "https:// S3 버킷 주소 /client_image/";
 
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = multiRequest.getFiles("upload[]");
        
        // 서버에 저장할 파일 이름
        String sysFileName = "";
        
        // 이름 형식 지정
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMDDHHss");
        Calendar calendar = Calendar.getInstance();
        sysFileName = simpleDateFormat.format(calendar.getTime());
 
        // 중복 방지
        for(int i=0; i<10; i++) {
            sysFileName += (char)((Math.random()*26)+97);
        }
        
        // 리스트로 받아온 파일을 하나씩 저장
        for(MultipartFile file : fileList){
            System.out.println(file.getOriginalFilename());
 
            // 순서 정렬을 위한 인덱스 추가 (날짜 + 인덱스)
            sysFileName += fileList.indexOf(file);
            
            // 기본 이름
            String orgFileName = file.getOriginalFilename();
 
            // 업로드할 파일의 풀 경로
            String orgFilePath = multiRequest.getServletContext().getRealPath("/");
            
            // 변경된 파일 이름으로 지정
            file.transferTo(new File(orgFilePath + File.separator + sysFileName + ".jpg"));
            
            // S3에 저장할 파일 생성
            File result = new File(orgFilePath + File.separator + sysFileName + ".jpg");
 
            // 업로드 위치 (S3 주소)
            awsS3.upload(result, "client_image/"+sysFileName + ".jpg");
            
            // 데이터 삽입
            ImageVO imvo = new ImageVO();
            
            imvo.setImageId(sysFileName);
            imvo.setImageName(sysFileName + ".jpg");
            imvo.setImageDir(clientUploadDir);
            
            // Status 입력해야 합니다.!
            imvo.setImageStatus("리뷰");
            imvo.setImageBy("client01");
            imvo.setWho("client");
            
            int pass = fileService.insertImage(imvo);
            
            if(pass > 0 ) {
                System.out.println("삽입 성공");
            } else {
                System.out.println("삽입 실패");
            }
            model.addAttribute("imvo", imvo);        
 
            // 이름에 추가한 인덱스 제거
            sysFileName = sysFileName.substring(0, sysFileName.length() -1);
        }
    }
}
 

 

insert_image 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.809.0.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.0.min.js" ></script>
 
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script type="text/javascript">
$(function(){
    //여기부터
    $("#fileUpload").change(function(){
        console.log($("#fileUpload")[0].files);
        
        fileList = $("#fileUpload")[0].files;
        fileListTag = '';
        
        fileImageTag = '';
        for(i = 0; i < fileList.length; i++){
            fileListTag += "<label for "+fileList[i].name+">"+ fileList[i].name +"</label><br>";
            fileImageTag += "<img src='"+URL.createObjectURL(fileList[i]) +
                    "' alt='"+fileList[i].name+"' id='" + fileList[i].name + 
                    "' style='width:auto; height:150px;'>";
        }
        $('#fileList').html(fileListTag);
        $('#imageList').html(fileImageTag);
    });
    //여기까지 
});
</script>
</head>
<body>
    <form method="post" action="insertImage.do" enctype="multipart/form-data">
        <input type="file" id="fileUpload" name="upload[]" multiple>
        <!-- 여기에 파일 목록 태그 추가 -->
        <ul id="fileList"></ul>
        <ul id="imageList"></ul>
        <input type="hidden" name="fileList" value="${ fileList }">
        <input type="submit" value="send">
    </form>
<br><br><br><hr><br><br><br>
 
</body>
</html>

 

 

 

실행하기

 

 

이미지 선택

 

 

페이지는 연결하지 않았으므로 오류가 발생합니다.

 

S3 확인 : 클라우드에 이미지 업로드 성공

 

MySQL 확인 : 테이블에 데이터 삽입 성공

 

반응형