django用layui组件上传图片

2022-08-01,,,

项目背景:

最近想把之前做的一个图片分类深度学习模型做一个简单的展示页面,于是打算用django框架写一个上传图片,返回处理结果的网页demo,然后部署到阿里云中。

导入layui
在项目中创建static目录,将layui文件放入该文件中。如下:
接下来需要给static文件夹配置路径:在settings.py文件中加入以下代码

STATIC_URL = '/static/'
STATIC_ROOT = ''
STATICFILES_DIRS = ( os.path.join('static'), )

在template中创建home.html,写一个简单的上传文件的前端

<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" href="{% static 'layui/css/layui.css' %}"  media="all">
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../static/layui/layui.js"></script>
</head>
<body>
{% csrf_token %} {#如果不加这个,程序会报错#}
<button type="button" class="layui-btn" id="test1">{#调用layui的上传文件组件#}
  <i class="layui-icon"></i>上传图片
</button>

{#<script src="/static/jQuery.js"></script>#}
<script src="/static/layui/layui.js"></script>
<script>
layui.use('upload', function(){
  var upload = layui.upload;
  $ = layui.$   //注意要定义$,该符号不是jQuery中的$
    var locate = document.getElementById("resContainer");  
  //执行实例
  var uploadInst = upload.render({
    elem: '#test1' //绑定元素
    ,url: '/upload/' //上传接口,需要在views.py中配置这个接口
    ,data:{ //需要上传这个data,不然程序也会报错
        'csrfmiddlewaretoken':function(){
            return $(':input:first').val()
        }
      }
      ,done: function(res){
      //上传完毕回调
          console.log(res);
          var i = new Image(); //新建image对象,从而将文件url转换为图片
          i.src = res.img_name;
          document.body.appendChild(i);//将后端返回的图片加入到页面中
          content = "该植被是"+res.code+"的";
          locate.append(content);
    }
    ,error: function(){
      //请求异常回调
    }
  });
});
</script>
<div id="resContainer">

</div>
</body>
</html>

接下来配置后端代码:

在urls.py中加入:

urlpatterns = [
    # path('admin/', admin.site.urls),
    path('home/',views.home),
    url(r'^upload',views.upload)
]

在views.py中配置upload接口:

def upload(request):
    if request.method == 'POST':
        file = request.FILES.get('file') #获取前端上传的文件
        print(file)
        fix = datetime.now().strftime('%Y%m%d%H%M%S%f')+'1' #给文件加前缀防止文件名重复
		#以下用绝对路径存储文件,之前我用相对路径一直写不对
        curPath = os.path.abspath( os.path.dirname( __file__ ) )
        # InfoServiceSystem是项目名
        rootPath = curPath[ :curPath.find( "itemplus\\" ) + len( "itemplus\\" ) ]
        img_path = os.path.abspath(rootPath+'/static/'+fix+file.name)
        #返回给前端的图片路径用相对路径,前端用绝对路径反而加载不了图片
        img_path_res = '/static/'+fix+file.name
        f = open(img_path,'wb')
        for i in file.chunks():
            f.write(i)
        f.close()
        res = imgClassify_main(img_path) //这个是我用来处理图片的深度模型接口,你们可以换成其他的
        if(res == 1):
            return JsonResponse({'img_name':img_path_res,'code':'健康'})
        else:
            return JsonResponse({'img_name':img_path_res,'code':'不健康'})

最终效果图如下:

也可以将该项目在服务器部署。到此结束,希望大家批评指正。

本文地址:https://blog.csdn.net/qq_36801317/article/details/107436563

《django用layui组件上传图片.doc》

下载本文的Word格式文档,以方便收藏与打印。