【Django后端分离】使用element-ui文件上传

1:导入element

    <!-- 引入样式 -->
    <link rel="stylesheet" href=https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src=https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.min.js"></script>
    <!-- 引入Vue -->
    <script src=https://unpkg.com/element-ui/lib/index.js"></script>

2:前端文件

css:
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: 409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: 8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }


html:
    {% comment %}      上传图片   {% endcomment %}
    <div id=profile">
        <h1 style=text-align: center" >更新社团封面</h1>
        <div id=app" style=">
            <el-upload
            :data= "datas"              // 携带的参数
            :headers="headers" // 请求头 name
=image" {% comment %} 后端接收的参数名 {% endcomment %} class=avatar-uploader" action="/show/images/" {% comment %} 上传路由地址 {% endcomment %} :show-file-list=false :on-success=handleAvatarSuccess" {% comment %} 文件上传成功时的钩子 {% endcomment %} :before-upload=beforeAvatarUpload"> {% comment %} 上传文件之前的钩子,参数为上传的文件 {% endcomment %} <img v-if=imageUrl" :src=" avatar"> <i v-else el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </div> {% comment %} 上传图片 {% endcomment %} # JS: <script> var Main = { data() { return {
          headers:{},// 请求头是个对象
          datas:{},// 对象 imageUrl:
'' }; },

    create(){
          this.headers.authenticate = sessionStorage.getItem('token')   // 设置请求头带token
          this.datas.data = "userHead"   // 设置请求参数
    }
     methods: { handleAvatarSuccess(res,file) { this.imageUrl
= URL.createObjectURL(file.raw); console.log(,this.imageUrl) },beforeAvatarUpload(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error(上传头像图片只能是 JPG 格式!); } (!isLt2M) { this.$message.error(上传头像图片大小不能超过 2MB!return isJPG && isLt2M; } } } var Ctor = Vue.extend(Main) new Ctor().$mount(#app) </script>

3:后端文件

路由:
# 预览图片
url("show/images/$",add_image.Image.as_view()),

py文件:


from
rest_framework.views import APIView from SocietyPlat settings from django.shortcuts render,redirect,HttpResponse from Databases models from django.http JsonResponse os 获取相对路径 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class Image(APIView): def post(self,request): 接收文件 file_obj = request.FILES.get(data') 用户名 username = str(request.data.get("username")) username = Wang" print(file_obj 判断是否存在文件夹 head_path = BASE_DIR + \\media\\{}\\head".format(username).replace(" ","") head_path 如果没有就创建文件路径 if not os.path.exists(head_path): os.makedirs(head_path) print("文件名",file_obj.name) # 文件名 name.png # print("文件二进制",file_obj.read()) # 文件二进制 b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x0 print("判断文件> 2.5M",file_obj.multiple_chunks(chunk_size=None)) # 文件大小 False小于2.5M print("文件大小",file_obj.size) # 文件大小 12651 print("文件编码",file_obj.charset) # None print("随文件一起上传的内容类型标题",file_obj.content_type) # image/png print("包含传递给content-type标头的额外参数的字典",file_obj.content_type_extra) # {} print("text/content-types提供的utf8字符集编码",file_obj.charset) # None # 图片后缀 head_suffix = file_obj.name.split(.")[1] 图片后缀 图片后缀 png 储存路径 file_path = head_path + \\{}".format(head." + head_suffix) file_path = file_path.replace(储存路径 C:\Users\user\Desktop\DownTest\media\username\head\head.png 上传图片 with open(file_path,1)">wb) as f: for chunk in file_obj.chunks(): f.write(chunk) message = {} message[code'] = 200 返回图片路径 back_path = \static\{}\head\{}'.format(username,1)">" + head_suffix).replace() message['] = back_path return JsonResponse(message)

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


注:所有源代码均实测运行过。所有源代码均已上传CSDN,请有需要的朋友自行下载。
继承APIView和ViewSetMixin;作用也与APIView基本类似,提供了身份认证、权限校验、流量管理等。ViewSet在开发接口中不经常用。
一、Django介绍Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位。许多成功的网站和APP都基于Django。Django 是一个开放源代码的 Web 应用框架,由 Python 写成。Django 遵守 BSD 版权,初次发布于 2005 年 7 月, 并于 2008 年 9 月发布了第一个正式版本 1.0 。Django学习线路Django 采用了 MVT 的软件设计模式,即模型(Model),视图(View)和模板(Template)。这个MVT模式并
本文从nginx快速掌握到使用,gunicorn快速掌握到使用,实现小白快速搭建django项目,并对可能出现的报错进行了分析
uniapp微信小程序订阅消息发送服务通知
Django终端打印SQL语句 1 Setting配置: 2 默认python 使用的MysqlDB连接,Python3 支持支持pymysql 所有需要在app里面的__init__加上下面配置:
url: re_path(&#39;authors/$&#39;, views.AuthorView.as_view()), re_path(&#39;book/(?P\d+)/$&#39;, vie
前提 关于html寻找路线: template 如果在各个APP中存在, Django 会优先找全局template 文件下的html文件,如果全局下的template文件没有相关的html Djan
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
from bs4 import BeautifulSoup#kindeditordef kindeditor(request): s = &#39;&#39;&#39; &lt;li&gt;&lt;s
view.py 配置 html 配置
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
浏览器有一个很重要的概念——同源策略(Same-Origin Policy)。所谓同源是指,域名,协议,端口相同。不同源的客户端脚本(javascript、ActionScript)在没明确授权的情况
自动发送 &gt; 依赖jQuery文件 实例--&gt;GET请求: 手动发送 &gt; 依赖浏览器XML对象(也叫原生ajax) Ajax主要就是使用 【XmlHttpRequest】对象来完成请
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render