flask之文件上传

1、创建表单提交页面,如:upload.html

<html>
<head>
  <title>File Uploadtitle>
head>
<body>
    <form action="http://localhost:8888/uploadfile" method="POST" enctype="multipart/form-data">
        <input type="file" name="file001"  />
        <input type="submit" value="提交" />
    form>
body>
html>

2、url地址关联表单提交页面

@app.route('/upload')
def uploadFile():
    return render_template('upload.html')

3、提交表单后定义执行保存的函数

@app.route('/uploadfile',methods=['GET','POST'])
def save():
    if request.method == 'POST':
        f = request.files['file001'] #提取文件
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))

4、完整演示代码

from flask import Flask, render_template, request
from werkzeug.utils import secure_filename

import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'upload/'   #app.config['UPLOAD_FOLDER'] 定义上传文件夹的路径 

@app.route('/upload')
def uploadFile():
    return render_template('upload.html')

@app.route('/uploadfile',methods=['GET','POST'])
def save():
    if request.method == 'POST':
        f = request.files['file001'] #提取文件
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))  #保存文件,目标文件的名称可以是硬编码的,也可以从 ​request.files[file] ​对象的​ filename ​属性中获取。但是,建议使用 ​secure_filename()​ 函数获取它的安全版本。
        return 'file uploaded successfully'
    else:
        return render_template('upload.html')

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

你可能感兴趣的:(Flask,flask,python,文件上传)