Python 实现简单的文件上传于下载功能

Python 实现简单的文件上传于下载功能

话不多说,直接上菜

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#pip3 isntall flask
import os, sys
from flask import Flask, render_template, request, send_file, send_from_directory
app = Flask(__name__)
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
@app.route("/")
def index():
    html="""<html>
          <title>File Upload</title>
        </head>
            <form action="/upload" method="POST" enctype="multipart/form-data">
                <input type="file" name="file" multiple="multiple" />
                <input type="submit" value="提交" />
            </form>
        </body>
        </html>"""
    return html
@app.route("/upload", methods=["POST"])
def upload_file():
        # f = request.files["file"]
        for f in request.files.getlist('file'):
            filename = os.path.join(BASE_PATH, "upload", f.filename)
            print(filename)
            f.save(filename)
        return "file upload successfully!"
    except Exception as e:
        return "failed!"
@app.route("/download/<filename>", methods=["GET"])
def download_file(filename):
    dir = os.path.join(BASE_PATH, 'download')
    return send_from_directory(dir, filename, as_attachment=True)
def mkdir(dirname):
    dir = os.path.join(BASE_PATH, dirname)
    if not os.path.exists(dir):
        os.makedirs(dir)