본문 바로가기
유용한정보&팁

Flask python 활용해 내 서버에 이미지 업로드

by cdling86 2023. 3. 24.
반응형

Flask를 활용해 내 서버에 이미지 업로드 

app.py

from flask import Flask, flash, request, redirect, url_for, render_template
import urllib.request
import os
from werkzeug.utils import secure_filename
 
app = Flask(__name__)
 
UPLOAD_FOLDER = 'static/uploads/'
 
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
 
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'txt', 'pdf'])
 
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
     
 
@app.route('/')
def home():
    return render_template('index.html')
 
@app.route('/', methods=['POST'])
def upload_image():
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('이미지 파일 선택해주세요')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #print('upload_image filename: ' + filename)
        flash('이미지 주소 복사 사용하세요.')
        return render_template('index.html', filename=filename)
    else:
        flash('Allowed image types are - pdf, txt, png, jpg, jpeg, gif')
        return redirect(request.url)
 
@app.route('/display/<filename>')
def display_image(filename):
    #print('display_image filename: ' + filename)
    return redirect(url_for('static', filename='uploads/' + filename), code=301)
 
if __name__ == "__main__":
    app.run(host='0.0.0.0')

index.html

 

<html>
<head>
<title>이미지 업로드</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
    <p>
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            <ul>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}
    </p>
    {% if filename %}
        <div>
            <img src="{{ url_for('display_image', filename=filename) }}">
        </div>
    {% endif %}
    <form method="post" action="/" enctype="multipart/form-data">
        <dl>
            <p>
                <input type="file" name="file" class="form-control" autocomplete="off" required>
            </p>
        </dl>
        <p>
            <input type="submit" value="업로드" class="btn btn-info">
        </p>
    </form>
</div>
</div>
</body>
</html>

플라스크를 활용해 내 서버에 이미지를 업로드를 하는 간단한 소스 코드입니다. 업로드 한 이미지의 url이 필요할 경우 이미지 우클릭 이미지 주소 복사해서 사용할 수 있습니다.

반응형

댓글