实现简单的文件上传于下载功能(支持多文件上传)
#!/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