Flask 上传文件到服务器
<!-- .html -->
<form action="/upload_file/" method="POST" enctype='multipart/form-data' >
<input type="file" class="input-file " name="file">
<button>上传</button>
</form>
注意:
在使用包含文件上传控件的 form 时,必须添加
enctype='multipart/form-data'
用于发送二进制的文件, 不对字符编码。
# .py
from flask import Flask,render_template,request,redirect,url_for
import os
app = Flask(__name__)
@app.route('/upload_file', methods=['POST'])
def upload_file():
if request.method == 'POST':
files = request.files.get('file')
f = request.files['file']
upload_path = os.path.join(os.path.dirname(__file__), 'imgs', f.filename)
f.save(upload_path)
return redirect(url_for('upload_file'))
return render_template('upload.html')