Flask--文件上传代码

# upload.py
from flask import Flask, request, render_template, url_for, redirect
from werkzeug.utils import secure_filename
import os


app = Flask(__name__)


@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        f = request.files['file']   # 必须与中'file'保持一致
        basepath =   # 当前文件所在路径
        upload_path = os.path.join(os.path.dirname(__file__) + '/static/uploads', secure_filename(f.filename)) #注意:没有的文件夹一定要先创建,不然会提示没有该路径
        f.save(upload_path)
        return redirect(url_for('upload'))
    return render_template('upload.html')


if __name__ == '__main__':
    app.run(debug=True)  
# upload.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>
<body>
    
    <form action="" method="POST" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="上传">
    form>
body>
html>

你可能感兴趣的:(Flask,flask,python)