实现文件上传功能


1、index.html

<form action="" method="post" enctype="multipart/form-data">
  <table>
    <tbody>
    <tr>
      <td>上传图片:</td>
      <td><input type="file" name="pic"></td>
    </tr>
    <tr>
      <td>图片名称:</td>
      <td><input type="text" name="picname"></td>
    </tr>
    <tr>
      <td></td>
      <td><input type="submit" value="立即提交"></td>
    </tr>
    </tbody>
  </table>
</form>
{% if picname %}
  {{ picname }} 上传成功
{% endif %}

2、app.py

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

app = Flask(__name__)

UPLOAD_PATH = os.path.join(os.path.dirname(__file__), 'static/uploads')

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('index.html')
    else:
        pic = request.files.get('pic')
        picname = request.form.get('picname')
        filename = secure_filename(pic.filename)
        pic.save(os.path.join(UPLOAD_PATH, filename))
        return render_template('index.html', picname=picname)

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

results matching ""

    No results matching ""