1、单个文件与多个文件上传与接收
# -*- coding:utf-8 -*-
# coding=utf8
import logging
import cv2
import numpy as np
from flask import jsonify, Flask, request, Response, render_template
from werkzeug.utils import secure_filename
from werkzeug.exceptions import RequestEntityTooLarge
from predict import main
import os
import datetime
from gevent import pywsgi
app = Flask(__name__,template_folder='./')
app.config['MAX_CONTENT_LENGTH'] = 20 * 1024 * 1024
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
@app.route('/', methods=['GET'])
def index():
return render_template('test.html')
@app.route('/Upload', methods=['POST'])
def upload():
try:
upload_file = request.files['imageFile']
file_name = secure_filename(upload_file.filename)
basedir = './static/img/'
if os.path.exists(basedir):
pass
else:
os.mkdir(basedir)
file_path = basedir + file_name
upload_file.save(file_path)
result,pred_proba=main(file_path)
json_result={'result':result,'probability':pred_proba.tolist()}
return jsonify(json_result)
except RequestEntityTooLarge as e:
returnStatus = '0'
allowedsize = app.config['MAX_CONTENT_LENGTH'] / 1024 / 1024
returnMessage = '上传图像过大,图像应低于 ' + str(allowedsize) + ' M'
json_result = {'returnStatus': returnStatus, 'returnMessage': returnMessage}
return jsonify(returnResult=json_result)
@app.route('/Upload_multi', methods=['POST'])
def upload_multi():
upload_files = request.files.getlist('image')
basedir2 = './static/folder/'
result_list=[]
for file in upload_files:
filename2 = secure_filename(file.filename)
upload_path = basedir2 + filename2
file.save(upload_path)
result, pred_proba = main(upload_path)
result_list.append(result+':'+str(pred_proba.tolist()))
return jsonify(returnResult=result_list)
if __name__ == '__main__':
#server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
#server.serve_forever()
app.run()
2、对应网页代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>脑胶质瘤二分类</title>
</head>
<body align=center>
<form action='/Upload' method='post' enctype='multipart/form-data'>
<input type='file' name='imageFile'>
<input type='submit' value='上传图像'>
</form>
<form action='/Upload_multi' method='post' enctype='multipart/form-data'>
<input type="file" webkitdirectory accept="image/*" name="image">
<input type="submit" value="上传文件夹">
</form>
</body>
</html>
参考文章:
(16条消息) 使用Flask服务部署算法模型_爱学习的小奶狗的博客-CSDN博客(16条消息) Python Flask文件服务器,同时接收多个文件_风正吹的博客-CSDN博客