zoukankan      html  css  js  c++  java
  • 基于Python flask web上传下载文件

    实现简单的文件上传于下载功能(支持多文件上传)

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-

    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>
    <head>
    <title>File Upload</title>
    </head>
    <body>
    <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():
    try:
    # 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)


    if __name__ == "__main__":
    mkdir('download')
    mkdir('upload')
    app.run(host="0.0.0.0", port=8000, debug=False)

      

     上传文件

    curl -F "file=@hello.txt" http://127.0.0.1:8000/upload

    下载文件

    wget http://127.0.0.1:8000/download/test.csv

  • 相关阅读:
    windows7上使用docker容器
    centos7 docker镜像加速器配置
    用列表生成器打印九九乘法表
    -bash: wget: command not found的两种解决方法
    centos7 Dockerfile安装nginx
    centos6.5关闭防火墙命令
    centos7开机启动tomcat7
    centos7安装tomcat7
    CentOS7防火墙firewalld
    poj_3662 最小化第k大的值
  • 原文地址:https://www.cnblogs.com/boye169/p/14071621.html
Copyright © 2011-2022 走看看