上传是是一个应用中不可或缺的功能,之前用thinkphp写过一个,这次使用Flask框架也写了一个,记录下代码,方便下次自己查阅,layui上传模块还比较简单,主要是接口返回的格式要按照他的要求来规范,不然就算上传成功也会提示上传接口异常,下面看我的事例代码
首先是前端的代码:
<div class="layui-input-inline" style="width: 100px;">
<button type="button" class="layui-btn" id="upload">
<i class="layui-icon"></i>上传文件
</button>
</div>
//js内容
<script>
layui.use(['jquery','layer','upload','code'], function(){
var layer = layui.layer
,upload = layui.upload
,$ = layui.jquery;
var uploadInst = upload.render({
elem: '#upload' //绑定元素
,url: '{{ url_for("user.upload") }}' //上传接口
,accept: 'file'
,exts: 'txt|log' //允许上传的文件类型
,done: function(res){
//console.log(res)
$('#loglist').val(res.data.src); //填充到input框
}
,error: function(){
//请求异常回调
}
});
});
</script>然后端的函数代码是:
#需要导入的模块
from werkzeug.utils import secure_filename
#上传函数
@user.route('/upload', methods=['POST', 'GET'])
def upload():
if request.method == "POST":
#获取上传文件对象
f = request.files['file']
#今日附件目录
attchment_dir = time.strftime("%Y/%m/%d/", time.localtime())
upload_path = os.path.join("attchment/uploadfile/", attchment_dir)
#判断附件目录是否存在
isExist = os.path.exists(upload_path)
if not isExist:
#不存在就创建
os.makedirs(upload_path, 0o777)
#拼接文件相对路径
src = os.path.join(upload_path + secure_filename(f.filename))
f.save(src)
datas = {
"code":0,
"msg":"",
"data":{
"src":src
}
}
return jsonify(datas)以上就是flask+layui异步上传的方法代码分享!
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:https://sulao.cn/post/577
评论列表