Django后端分离 使用element-ui文件上传方式


Posted in Python onJuly 12, 2020

1:导入element

<!-- 引入样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" rel="external nofollow" >
  <!-- 引入组件库 -->
  <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="text-align: center">
      <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="imageUrl" class="avatar">
        <i v-else class="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("imageUrl",this.imageUrl)
      },

      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!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 import settings
from django.shortcuts import render, redirect, HttpResponse
from Databases import models
from django.http import JsonResponse
import 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('image',None)
 style = requetst.data.get('data')
    # 用户名
    # username = str(request.data.get("username"))
    username = "Wang"

    print("file_obj",file_obj.name)

    # 判断是否存在文件夹
    head_path = BASE_DIR + "\\media\\{}\\head".format(username).replace(" ","")
    print("head_path",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]
    print("图片后缀",head_suffix) # 图片后缀 png

    # 储存路径
    file_path = head_path + "\\{}".format("head." + head_suffix)
    file_path = file_path.replace(" ","")
    print("储存路径", file_path)  # C:\Users\user\Desktop\DownTest\media\username\head\head.png

    # 上传图片
    with open(file_path, 'wb') as f:
      for chunk in file_obj.chunks():
        f.write(chunk)

    message = {}
    message['code'] = 200
    # 返回图片路径
    back_path = '\static\{}\head\{}'.format(username,"head." + head_suffix).replace(" ","")
    message['image'] =  back_path

    return JsonResponse(message)

补充知识:django后台接口处理element-ui的el-upload组件form data类型数据

对于向我这样一只前端和后端的双咸鱼来说写一个不了解的接口实在是太难受了,前端不知道在哪找数据,后端又不知道处理什么样的数据。

现在有这样一个需求,我需要使用element-ui中的el-upload组件完成一个上传文件的功能。但是不知道是不是因为我没有发现,我翻遍了官网都没有找到这个组件点击上传以后发的是什么样的数据请求。

终于我好像突然想起来浏览器的开发者工具可以查看发出的请求

于是我们可以写这么一个组件来一探究竟:

Django后端分离 使用element-ui文件上传方式

点击上传到服务器以后前台就会发出请求,我们就可以使用devtool看具体的请求头等等数据,具体位置在这里:

Django后端分离 使用element-ui文件上传方式

点击这个upload,找一找,我们就会发现最下面有一个file

Django后端分离 使用element-ui文件上传方式

这应该就是我们要上传的文件。可以看见它是以form data的形式上传的。

所以我们就可以写对应的后端接口了。

这里给一个接口的demo

def writeFile(filePath, file):
  with open(filePath, "wb") as f:
    if file.multiple_chunks():
      for content in file.chunks():
        f.write(content)
    else:
      data=file.read() ###.decode('utf-8')
      f.write(data)

def uploadFile(request):
  if request.method == "POST": 
    fileDict = request.FILES.items()
    # 获取上传的文件,如果没有文件,则默认为None  
    if not fileDict:
      return JsonResponse({'msg': 'no file upload'})
    for (k, v) in fileDict:
      print("dic[%s]=%s" %(k,v))
      fileData = request.FILES.getlist(k)
      for file in fileData:
        fileName = file._get_name()
        filePath = os.path.join(settings.TEMP_FILE_PATH, fileName)
        print('filepath = [%s]'%filePath)
        try:
          writeFile(filePath, file)
        except:
          return JsonResponse({'msg': 'file write failed'})
    return JsonResponse({'msg': 'success'})

另外想要在前端获取后端返回的请求的话可以使用on-success、on-error、on-exceed这几个钩子函数,具体可以在element ui的官网找到

以上这篇Django后端分离 使用element-ui文件上传方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python单元测试框架unittest使用方法讲解
Apr 13 Python
Python fileinput模块使用实例
May 28 Python
举例详解Python中yield生成器的用法
Aug 05 Python
Python优化技巧之利用ctypes提高执行速度
Sep 11 Python
利用信号如何监控Django模型对象字段值的变化详解
Nov 27 Python
python如何让类支持比较运算
Mar 20 Python
Python简单生成随机数的方法示例
Mar 31 Python
python进阶之多线程对同一个全局变量的处理方法
Nov 09 Python
Python实现微信翻译机器人的方法
Aug 13 Python
Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签
Dec 04 Python
简单介绍django提供的加密算法
Dec 18 Python
python PIL/cv2/base64相互转换实例
Jan 09 Python
PyQt5-QDateEdit的简单使用操作
Jul 12 #Python
Python logging日志模块 配置文件方式
Jul 12 #Python
django rest framework 过滤时间操作
Jul 12 #Python
使用python脚本自动生成K8S-YAML的方法示例
Jul 12 #Python
python读取excel进行遍历/xlrd模块操作
Jul 12 #Python
django rest framework 自定义返回方式
Jul 12 #Python
Django+RestFramework API接口及接口文档并返回json数据操作
Jul 12 #Python
You might like
ThinkPHP发送邮件示例代码
2016/10/08 PHP
PHP CURL采集百度搜寻结果图片不显示问题的解决方法
2017/02/03 PHP
javascript 关闭IE6、IE7
2009/06/01 Javascript
jQuery live( type, fn ) 委派事件实现
2009/10/11 Javascript
jQuery学习3:操作元素属性和特性
2010/02/07 Javascript
jQuery之ajax删除详解
2014/02/27 Javascript
调整小数的格式保留小数点后两位
2014/05/14 Javascript
jQuery ajax应用总结
2016/06/02 Javascript
jQuery bt气泡实现悬停显示及移开隐藏功能的方法
2016/07/12 Javascript
JS模拟实现方法重载示例
2016/08/03 Javascript
js判断iframe中元素是否存在的实现代码
2016/12/24 Javascript
JS中touchstart事件与click事件冲突的解决方法
2018/03/12 Javascript
Array数组对象中的forEach、map、filter及reduce详析
2018/08/02 Javascript
分享vue里swiper的一些坑
2018/08/30 Javascript
原生JS实现DOM加载完成马上执行JS代码的方法
2018/09/07 Javascript
一些手写JavaScript常用的函数汇总
2019/04/16 Javascript
arctext.js实现文字平滑弯曲弧形效果的插件
2019/05/13 Javascript
Django中实现一个高性能计数器(Counter)实例
2014/07/09 Python
Python中使用pprint函数进行格式化输出的教程
2015/04/07 Python
Python找出9个连续的空闲端口
2016/02/01 Python
Python中input与raw_input 之间的比较
2017/08/20 Python
pycharm的console输入实现换行的方法
2019/01/16 Python
通过代码简单了解django model序列化作用
2020/11/12 Python
Python + opencv对拍照得到的图片进行背景去除的实现方法
2020/11/18 Python
用pushplus+python监控亚马逊到货动态推送微信
2021/01/29 Python
德国拖鞋网站:German Slippers
2019/11/08 全球购物
公司成本主管岗位责任制
2014/02/21 职场文书
赡养老人协议书
2014/04/21 职场文书
勾股定理课后反思
2014/04/26 职场文书
常住证明范本
2015/06/23 职场文书
2016年教师节感恩寄语
2015/12/04 职场文书
2016年学校综治宣传月活动总结
2016/03/16 职场文书
2019学校请假条格式及范文
2019/06/25 职场文书
python爬虫框架feapde的使用简介
2021/04/20 Python
vue实现简单数据双向绑定
2021/04/28 Vue.js
浅谈@Value和@Bean的执行顺序问题
2021/06/16 Java/Android