首先网上真的没有这方面的文章,用flask框架的可以看看这篇
https://fly.layui.com/jie/21522/
首先讲一下后台怎么获取到layui upload上传的文件
image.png
为什么get的(‘file’)这个,这时候我们打开浏览器上传完图片点击提交的时候,按F12点network,左侧找到你的方法名称,headers拉到底就能看到类似这样的,提交的from data里面有个file这个参数(此参数就是你上传的图片,layui可以用这个参数更改field:'任意',)详情的话点击上面的view source
image.png
好了不多说了,干货--->
setting.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') # media即为图片上传的根路径
MEDIA_URL = '/media/'
base.html(看不懂base.html的,我也救不了)
{% load static from staticfiles %}
{% block title %}
基础页{% endblock %}
{% block styles %}
{% endblock %}
{% block head %}
{% endblock %}
{% block body %}
{% endblock %}
{% block fooder %}
{% endblock %}
{% block scripts %}
{% endblock %}
test.html
{% extends 'base.html' %}
{% load static from staticfiles %}
{% block styles %}
.imgbos {
width: 200px;
height: 200px;
border: 3px solid #0099CC;
border-radius: 5px;
padding: 3px;
text-align: center;
display: flex;
align-items: center
}
.imgbos img {
max-width: 200px;
max-height: 200px;
margin: auto
}
{% endblock %}
{% block body %}
{% csrf_token %}{# 随机码 #}
名称
class="layui-input">
上传图片
立即提交
{% endblock %}
{% block scripts %}
layui.use(['form', 'layer', 'upload'], function () {
var layer = layui.layer;
var upload = layui.upload;
var $ = layui.jquery;
var img_url = ''
upload.render({
elem: '#upload', //上传图标
url: '{{ path }}/test',
auto: false,//选择文件后不自动上传
bindAction: '#commit',
size: 20000,
//上传前的回调
before: function (obj) {
this.data = {
img_name: $('input[name="img_name"]').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
}
},
//选择文件后的回调
choose: function (obj) {
obj.preview(function (index, file, result) {
console.log(file.name)
$('#preview').attr('src', result);
$('#preview').attr('title', file.name);
})
},
//操作成功的回调
done: function (res, index, upload) {
var code = res.code === 0 ? 1 : 2;
layer.alert(res.msg, {icon: code}, function () {
parent.window.location.reload();
})
console.log(res)
},
//上传错误回调
error: function (res, index, upload) {
layer.alert('上传失败!' + res);
}
});
})
{% endblock %}
views.py
from sysmanage.models import Test
from django.http import JsonResponse
@csrf_protect
def test(request):
path = request.scheme + "://" + request.get_host() # url
ff_path = request.scheme + "://" + request.get_host() + request.path # 加方法url
if request.method == 'GET':
return render(request, "test.html", {'ff_path': ff_path, 'path': path, })
else:
img_name = request.POST.get('img_name')
img_url = request.FILES.get('file')
print(img_url)
img = Test(img_name=img_name, img_url=img_url)
img.save()
response_data = {"info": "成功更新角色编辑按钮"}
return JsonResponse(response_data)
urls.py
from django.urls import path
from #自己的app名称 import views
path('test', views.test), # 测试页面