머신러닝 프로젝트가 생각보다 빨리 끝나서,

클라이언트 - 서버 - 서버(ai 계산)의 구조로 서비스를 만들려고 한다.

그래서 가장 먼저 클라이언트에서 서버로 이미지를 전송하는 기능을 구현했다.


소스코드

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
from flask import Flask, render_template, request, redirect, url_for
from flaskext.mysql import MySQL
from werkzeug.utils import secure_filename
 
import os
 
mysql = MySQL()
app = Flask(__name__)
 
# 데이터베이스 값 설정
app.config['MYSQL_DATABASE_USER'= 'root'
app.config['MYSQL_DATABASE_PASSWORD'= '0000'
app.config['MYSQL_DATABASE_DB'= 'image'
app.config['MYSQL_DATABASE_HOST'= 'localhost'
app.secret_key = "ABCDEFG"
mysql.init_app(app)
 
@app.route('/', methods=['GET''POST'])
def main():
    return render_template('main.html')
 
@app.route('/fileUpload', methods = ['GET''POST'])
def file_upload():
    if request.method == 'POST':
        f = request.files['file']
        f.save('static/uploads/' + secure_filename(f.filename))
        files = os.listdir("static/uploads")
 
        conn = mysql.connect()
        cursor = conn.cursor()
        # 파일명과 파일경로를 데이터베이스에 저장함
        sql = "INSERT INTO images (image_name, image_dir) VALUES ('%s', '%s')" % (secure_filename(f.filename), 'uploads/'+secure_filename(f.filename))
        cursor.execute(sql)
        data = cursor.fetchall()
 
        if not data:
            conn.commit()
            return redirect(url_for("main"))
 
        else:
            conn.rollback()
            return 'upload failed'
 
        cursor.close()
        conn.close()
 
@app.route('/view', methods = ['GET''POST'])
def view():
    conn = mysql.connect()  # DB와 연결
    cursor = conn.cursor()  # connection으로부터 cursor 생성 (데이터베이스의 Fetch 관리)
    sql = "SELECT image_name, image_dir FROM images"  # 실행할 SQL문
    cursor.execute(sql)  # 메소드로 전달해 명령문을 실행
    data = cursor.fetchall()  # 실행한 결과 데이터를 꺼냄
 
    data_list = []
 
    for obj in data:  # 튜플 안의 데이터를 하나씩 조회해서
        data_dic = {  # 딕셔너리 형태로
            # 요소들을 하나씩 넣음
            'name': obj[0],
            'dir': obj[1]
        }
        data_list.append(data_dic)  # 완성된 딕셔너리를 list에 넣음
 
    cursor.close()
    conn.close()
 
    return render_template('view.html', data_list=data_list)  # html을 렌더하며 DB에서 받아온 값들을 넘김
 
if __name__ == '__main__':
    app.run(port=80)
 
cs

 

main.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image Upload</title>
</head>
<body>
    <p>
        <form action="http://localhost:80/fileUpload" method="POST" enctype = "multipart/form-data">
        <input type = "file" name = "file" />
        <a href="/view" onclick="return confirm('제출 성공! \n업로드한 이미지를 확인합니다.');">제출하기</a>
    </p>
</body>
</html>
cs

 

view.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>view image</title>
</head>
<body>
    <h1> 업로드 된 이미지들 </h1>
 
    <p>
         <button type="button" onclick="location.href='/' ">뒤로가기</button>
    </p>
 
    {% for obj in data_list%}
        <p>
            <img src="{{ url_for('static', filename=obj.dir) }}" width="175" height="175">
        </p>
    {% endfor %}
</body>
</html>
cs

 

mysql에서 blob를 사용하면 데이터베이스에 이미지를 넣을 수 있다고 봤는데,

엄청 구린 방법이라고 해서, 서버에 파일을 저장하는 방식으로 구현했다.

 

그리고 데이터베이스에는 해당 이미지명과 경로를 저장해서

html에서 불러올때 이미지 경로로 불러올 수 있게 했다.

 

결과

이미지 업로드
업로드 성공
결과

+ Recent posts