본문 바로가기
PRACTICE/Basic

[Flask] File Uploading 예제 (파일 제출 안할 경우 flash로 에러메시지 출력)

by 1005 2020. 9. 24.

 

 

Uploading Files — Flask Documentation (1.1.x)

Uploading Files Ah yes, the good old problem of file uploads. The basic idea of file uploads is actually quite simple. It basically works like this: A tag is marked with enctype=multipart/form-data and an is placed in that form. The application accesses th

flask.palletsprojects.com

 

 

Flask – File Uploading - Tutorialspoint

Flask – File Uploading Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to ‘multipart/form-data’, posting the file to a URL. The URL handler fetches file from request.files[] object and saves it to the

www.tutorialspoint.com

 

< app.py >

 

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
import os #운영체제에서 제공되는 여러 기능을 파이썬에서 수행할 수 있게 해줌.
from flask import Flask, flash, request, redirect
from flask import url_for, render_template
from werkzeug.utils import secure_filename
 
app = Flask(__name__)
app.secret_key = 'random string' #프레임워크 상에서 꼭 넣으라고 요구함.
 
@app.route('/upload')
def upload_file():
   return render_template('upload.html')
    
@app.route('/uploader', methods = ['GET''POST'])
def uploader(): 
   if request.method == 'POST':
      #제출 요청한 파일이 있는지 확인
      if request.files['file'].filename == '':
          flash('파일이 없습니다. 파일을 제출하세요!'
          # 파일이 없으면 flash 전달. (현재 창에서 flash 메시지 출력.) 
          return redirect(url_for('upload_file'))
      # if request.files['file'].filename == '':  
      #    return '파일이 존재하지 않습니다.'
 
      # 파일이 존재한다면
      file = request.files['file'#request.files: 단일 파일 
      file.save(secure_filename(file.filename))
      # file.filename: 업로드한 파일 이름
      # secure_filenmae: 파일이름을 보안 처리
      # file.save: 인자값으로 경로가 없으면 py파일과 같은 경로에 저장됨.
      return '파일 업로드 성공!!'
        
if __name__ == '__main__':
   app.run(host='0.0.0.0', port = 80, debug = True)

 

 

 

< upload.html >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
   <body>
      <form action = "http://localhost/uploader" method = "POST" 
         enctype = "multipart/form-data">
         <!-- multipart/form-data: 모든 문자를 인코딩하지 않음을 명시함. -->
         <!-- <form> 요소가 파일이나 이미지를 서버로 전송할 때 사용함. -->
         <!-- 이 코드를 작성하지 않으면 파일의 이름만 전송되고 파일 데이터는 전송되지 않음.-->
         <input type = "file" name = "file" />
         <input type = "submit"/>
         <br>
 
         {% with messages = get_flashed_messages() %} 
         {% if messages %}
             <ul>
               {% for msg in messages %}
                <li><strong>Error: </strong>{{ msg }}</li> <!--flash 메시지 출력-->
                {% endfor %}
             </ul>
         {% endif %}
         {% endwith %}
 
      </form>
   </body>
</html>

 

 

 

파일을 선택하지않고 '제출'버튼을 누르면

flash를 통해 에러메시지가 출력된다.  

 

 

 

업로드가 성공하면 파이썬코드와 같은 경로에 업로드한 Setup.log 파일이 포함된 것을 확인할 수 있다. 

 

 

 

'PRACTICE > Basic' 카테고리의 다른 글

[C] 성적 구하는 프로그램 (난수, 다차원 배열 사용)  (0) 2020.11.10
[Flask] SQLite 예제  (0) 2020.09.24
[Flask] Message Flashing 예제  (0) 2020.09.24
[Flask] Redirect & Errors 예제  (0) 2020.09.24
[Flask] Sessions 예제  (0) 2020.09.24

댓글