最近测试的时候需要模拟一个文件服务器,支持文件的上传和下载功能。百度了一下各位大神的博客,结合公司的实际情况,写了一个文件服务器。
环境信息:python3.7.4 + Flask(1.1.1)
测试工具:requests(2.22.0)
目录结构:
image.png
代码如下:
import os
from string import Template
from flask import Flask, request, send_file
from werkzeug.utils import secure_filename
app = Flask(__name__)
pwd = os.path.dirname(__file__)
#定义文件的保存路径和文件名尾缀
UPLOAD_FOLDER = os.path.join(pwd,'save_file')
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
HOST = "192.168.52.235"
PORT = 5000
@app.route('/index')
def index():
"""
返回一个网页端提交的页面
:return:
"""
html = Template("""
<!DOCTYPE html>
<html>
<body>
<form action = "http://$HOST:$PORT/upload" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
</body>
</html>
""")
html = html.substitute({"HOST": HOST, "PORT": PORT})
return html
def allowed_file(filename):
"""
检验文件名尾缀是否满足格式要求
:param filename:
:return:
"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
"""
上传文件到save_file文件夹
以requests上传举例
wiht open('路径','rb') as file_obj:
rsp = requests.post('http://localhost:5000/upload,files={'file':file_obj})
print(rsp.text) --> file uploaded successfully
"""
if 'file' not in request.files:
return "No file part"
file = request.files['file']
if file.filename == '':
return 'No selected file'
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'file uploaded successfully'
return "file uploaded Fail"
@app.route("/download")
def download_file():
"""
下载src_file目录下面的文件
eg:下载当前目录下面的123.tar 文件,eg:http://localhost:5000/download?fileId=123.tar
:return:
"""
file_name = request.args.get('fileId')
file_path = os.path.join(pwd,'src_file',file_name)
if os.path.isfile(file_path):
return send_file(file_path,as_attachment=True)
else:
return "The downloaded file does not exist"
if __name__ == '__main__':
app.run(host=HOST, port=PORT)
通过浏览器上传:
1.打开web上传页
image.png
2.选择上传文件
image.png
3.点击提交,查看结果:
image.png
ps:如果save_file有同名的文件会直接覆盖,如果需做备份和报错处理,可自行研究(常用的文件操作)
通过requests上传,代码如下:
#文件服务器的测试脚本
import requests
URL="http://192.168.52.235:5000/upload"
f = open(r'D:\work\tools\file_server\templates\upload.html','rb')
rsp = requests.get(URL,files={'file':f})
print(rsp.text)
下载src_file下面的文件的url,get或者post都支持,浏览器直接打开,或者接口调用工具打开;
url:http://localhost:5000/download?fileId=tool.py
网友评论