flask文件上传

#coding=utf-8

import os
from flask import Flask
from flask import request
from flask import redirect
from flask import url_for
from flask import render_template
from werkzeug.utils import secure_filename

app = Flask(__name__)


@app.route("/upload", methods=["GET", "POST"])
def upload():
    if request.method == "POST":
        f = request.files.get("file")
        basepath = os.path.abspath(os.path.dirname(__file__))
        upload_path = os.path.join(basepath, r"static\uploads")
        #注意这里要传文件路径+文件名!
        f.save(os.path.join(upload_path, secure_filename(f.filename)))
        return redirect(url_for("upload"))
    return render_template("upload.html")


if __name__ == "__main__":
    app.run(port=8000, debug=True)


#upload.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Files</title>
</head>
<body>
    <form action="" method="post" enctype="multipart/form-data">
        <p>
            <input type="file" name="file">
            <input type="submit" valule="upload">
        </p>

    </form>

</body>
</html>

猜你喜欢

转载自www.cnblogs.com/themost/p/8988984.html