flask前端上传图片/文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/base.css">
<script type="text/javascript" src="/static/js/jquery-3.0.0.js"></script>
<title>Document</title>
</head>
<body>
————————————————————————————————————————————————————————————————————————————————————————————点击预测按钮,将选中的图片发送到后端,并进行识别预测————————————————————————————————————————————————————————————
<div class="page-header">
<h2>人工智能模型应用平台</h2>
</div>
<div class="panel panel-default image">
<div class="panel-heading">
<h3 class="panel-title">上传图片</h3>
</div>
<div class="panel-body">
<form action="" enctype='multipart/form-data' method='POST' class="img-form">
<input type="file" name="uploadfile" id="uploadfile" accept="image:wq/*" class="btn btn-info upload-file"/>
<div id="preview" class="preview">
<img class="imghead" id="imghead"/>
</div>
<br>
</form>
<div class="pic" role="form" id="res_pic">
<button type="button" class="btn btn-primary pre_btn" id="pre">预测</button>
<!-- {#显示结果#}-->
<div id="show_data"></div>
</div>
</div>
</div>
<script>
$(function () {
$("#imghead").click(function () {
$("#uploadfile").click();
});
$("#uploadfile").change(function () {
var files = $(this)[0].files[0];
if (files) {
var reader = new FileReader(); //调用FileReader
reader.onload = function (evt) { //读取操作完成时触发。
$("#imghead").attr('src', evt.target.result) //将img标签的src绑定为DataURL
};
reader.readAsDataURL(files); //将文件读取为 DataURL(base64)
} else {
alert("上传失败");
}
});
});
$('#pre').click(function () {
$('#show_data').empty();
var formData = new FormData;
var jqSender = $('#pre');
var value = $("#uploadfile")[0].files[0];
if (value == undefined) {
alert('请上传预测图片!');
return false;
}
formData.append('myfile', value);
var obj_name = $("#uploadfile")[0].files[0].name;
var extension = obj_name.split('.')[1].toLowerCase();
if (extension != "png" && extension != "jpg") {
alert('上传图片文件格式有误!');
return false;
}
$.ajax({
url: '/predict',
type: 'POST',
data: formData,
beforeSend: function () {
jqSender.hide().after('<img id="load" src="/static/gif/ci2.gif" />');
},
processData: false,
contentType: false,
success: function (data) {
data = JSON.parse(data);
console.log(data);
var pre_data = $("<img id='resimg' class='resimg' src='" + data.itemUrl + "'>");
$('#show_data').append(pre_data);
},
complete: function () {
$('#load').remove();
jqSender.show();
}
});
})
</script>
</body>
</html>
——————————————————————————————————————————————————————点击选择图片/文件按钮,同时将图片/文件发送到后端保存,当点击预测按钮时,从后端指定目录调取图片/文件,返回给前端显示————————————————————————————
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/base.css">
<script type="text/javascript" src="/static/js/jquery-3.0.0.js"></script>
<title>Document</title>
</head>
<body>
<div class="page-header">
<h2>人工智能模型应用平台</h2>
</div>
<div class="panel panel-default image">
<div class="panel-heading">
<h3 class="panel-title">上传图片</h3>
</div>
<div class="panel-body">
<form action="" enctype='multipart/form-data' method='POST' class="img-form">
<input type="file" name="uploadfile" id="uploadfile" accept="image:wq/*" class="btn btn-info upload-file"/>
<div id="preview" class="preview">
<img class="imghead" id="imghead"/>
</div>
<br>
</form>
<div class="pic" role="form" id="res_pic">
<button type="button" class="btn btn-primary pre_btn" id="pre">预测</button>
<!-- {#显示结果#}-->
<div id="show_data"></div>
</div>
</div>
</div>
<script>
$(function () {
$("#imghead").click(function () {
$("#uploadfile").click();
});
$("#uploadfile").change(function () {
var files = $(this)[0].files[0];
var formData = new FormData;
formData.append('ori_pic', files);
if (files) {
var reader = new FileReader(); //调用FileReader
reader.onload = function (evt) { //读取操作完成时触发。
$("#imghead").attr('src', evt.target.result) //将img标签的src绑定为DataURL
};
reader.readAsDataURL(files); //将文件读取为 DataURL(base64)
$.ajax({
url: '/savepic',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (res) {
console.log(res)
}
})
} else {
alert("上传失败");
}
});
});
$('#pre').click(function () {
$('#show_data').empty();
$.ajax({
url: '/predict',
type: 'POST',
data: '',
beforeSend: function () {
$('#pre').hide().after('<img id="load" src="/static/gif/ci2.gif" />');
},
processData: false,
contentType: false,
success: function (data) {
data = JSON.parse(data);
if (data.ok == true){
var pre_data = $("<img id='resimg' class='resimg' src='" + data.itemUrl + "'>");
$('#show_data').append(pre_data)
}else{
alert(data.msg);
return false;
}
},
complete: function () {
$('#load').remove();
$('#pre').show();
}
})
})
</script>
</body>
</html>
##############后端
@web.route('/predict', methods=['POST'])
def predict():
'''预测视图'''
from coco import session, model
with session.as_default():
saveImgDir = current_app.config['WEB_IMG_RES']
shutil.rmtree(saveImgDir)
os.mkdir(saveImgDir)
try:
imgDirList = os.listdir(settings.UPLOAD_FOLDER)
input_path = settings.UPLOAD_FOLDER + imgDirList[0]
start = time.time()
per_img_name = DealData().predictData(input_path, saveImgDir, model)
end = time.time()
print(end - start)
shutil.rmtree(current_app.config['UPLOAD_FOLDER'])
os.mkdir(current_app.config['UPLOAD_FOLDER'])
return json.dumps({
'ok': True,
'itemUrl': current_app.config['SHOW_IMG_URL'] + per_img_name
}).encode('utf8')
except Exception as e:
msg = {'ok': False, 'msg': '请重新选取图片!'}
return json.dumps(msg)
以上内容是个人记录一下。

浙公网安备 33010602011771号