<div>
<span>上传图片:</span>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon"></i>上传图片
</button>
<div class="layui-upload-list"></div>
<input type="submit" id ="abc" class="layui-btn layui-btn-radius layui-btn-normal" style="font-size: 25px;" value=下一步>
</div>
<script>
layui.use([‘upload‘, ‘jquery‘], function(){
var upload = layui.upload;
var $ = layui.jquery;
//执行实例
var uploadInst = upload.render({
elem: ‘#test1‘, //绑定元素
multiple: true,
method: ‘POST‘,
auto: false, //禁止自动上传
data: {
‘csrfmiddlewaretoken‘: function () { //POST方法需要进行验证 获取验证
return $(‘:input:first‘).val()
}
},
acceptMime: ‘image/*‘,
bindAction: "#abc", //绑定上传
url: "{% url ‘proved‘ %}", //上传接口
choose: function (obj) { //obj参数包含的信息,跟 choose回调完全一致
//将每次选择的文件追加到文件队列
files = obj.pushFile();
//layer.load(); //上传loading
obj.preview(function (index, file, result) {
$(".layui-upload-list").append(‘<img src="‘ + result + ‘" id="remove_‘ + index + ‘" title="双击删除该图片" style="width:200px;height:auto;">‘)
$(‘#remove_‘ + index).bind(‘dblclick‘, function () {//双击删除指定预上传图片
delete files[index];//删除指定图片
$(this).remove();
})
//console.log(1, index); //得到文件索引
//console.log(2, file.name); //得到文件对象
//console.log(3, result); //得到文件base64编码,比如图片
})
},
done: function (res) {
//imgs = imgs.concat(res.Data)
//console.log(imgs)
if (res.code==0) {
layer.msg("图片上传成功!", { icon: 1, time: 1000 }
//,function(){setTimeout(‘window.location.reload()‘,1000);} //上传成功后刷新页面
// window.location.href="{:url(‘test/index‘)}" //上传成功后跳转指定页面
);} //上传完毕回调
},
error: function () {
//请求异常回调
}
});
});
</script>
后台 views
import json
from django.http import JsonResponse
def proved(request):
if request.method ==‘GET‘:
return render(request,‘first/proved.html‘)
if request.method ==‘POST‘:
com_from = request.META.get("HTTP_REFERER") //前端验证
for f in request.FILES.getlist(‘file‘): //循环存储图片到库
pro = Prove()
pro.provePeople = request.user
pro.provePhoto = f
pro.save()
return JsonResponse({‘code‘: ‘0‘,‘msg‘: ‘OK‘}) //json返回 无返回前端会提示上传端口异常