Python flask 上傳圖片

markdown #說明 使用 python 套件 flask 實作圖片上傳與後台接收功能。 ##Code ``` # -*- coding: utf-8 -*- import os from flask import Flask, request, url_for, send_from_directory from werkzeug import secure_filename ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = os.getcwd() app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 html = ''' Upload File

圖片上傳

''' def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/uploads/') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) file_url = url_for('uploaded_file', filename=filename) return html + '
' return html if __name__ == '__main__': app.run() ``` ##DEMO
##REF - Code - 教學文

留言