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中常用信号signal类型实例
Jan 25 Python
Python计算时间间隔(精确到微妙)的代码实例
Feb 26 Python
python实现五子棋小程序
Jun 18 Python
python路径的写法及目录的获取方式
Dec 26 Python
pytorch中tensor.expand()和tensor.expand_as()函数详解
Dec 27 Python
使用TensorFlow搭建一个全连接神经网络教程
Feb 06 Python
python 6.7 编写printTable()函数表格打印(完整代码)
Mar 25 Python
python 3.8.3 安装配置图文教程
May 21 Python
Pytorch 高效使用GPU的操作
Jun 27 Python
Python调用C语言程序方法解析
Jul 07 Python
Python3.9.1中使用match方法详解
Feb 08 Python
Python列表删除重复元素与图像相似度判断及删除实例代码
May 07 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
探讨:使用XMLSerialize 序列化与反序列化
2013/06/08 PHP
调试WordPress中定时任务的相关PHP脚本示例
2015/12/10 PHP
浅谈PHP实现大流量下抢购方案
2017/12/15 PHP
PHP实现负载均衡session共享redis缓存操作示例
2018/08/22 PHP
如何用javascript去掉字符串里的所有空格
2007/02/08 Javascript
js indexOf()定义和用法
2012/10/21 Javascript
浅谈JSON和JSONP区别及jQuery的ajax jsonp的使用
2014/11/23 Javascript
使用console进行性能测试
2015/04/27 Javascript
jQuery获取DOM节点实例分析(2种方式)
2015/12/15 Javascript
AngularJS点击添加样式、点击变色设置的实例代码
2017/07/27 Javascript
vue element项目引入icon图标的方法
2018/06/06 Javascript
深入剖析JavaScript instanceof 运算符
2019/06/14 Javascript
[03:24]DOTA2超级联赛专访hao 大翻盘就是逆袭
2013/05/24 DOTA
Python使用Selenium爬取淘宝异步加载的数据方法
2018/12/17 Python
PYTHON EVAL的用法及注意事项解析
2019/09/06 Python
python基于gevent实现并发下载器代码实例
2019/11/01 Python
解决pycharm启动后总是不停的updating indices...indexing的问题
2019/11/27 Python
python 实现让字典的value 成为列表
2019/12/16 Python
Python ConfigParser模块的使用示例
2020/10/12 Python
html5中canvas学习笔记2-判断浏览器是否支持canvas
2013/01/06 HTML / CSS
html5实现九宫格抽奖可固定抽中某项奖品
2020/06/15 HTML / CSS
英国优质鞋类专家:Robinson’s Shoes
2017/12/08 全球购物
波兰最大的宠物用品网上商店:FERA.PL
2019/08/11 全球购物
Lentiamo比利时:便宜的隐形眼镜
2020/02/14 全球购物
施工人员岗位职责
2013/12/12 职场文书
毕业生简历自我评价范文
2014/04/09 职场文书
《最佳路径》教学反思
2014/04/13 职场文书
乡镇精神文明建设汇报材料
2014/08/15 职场文书
高中教师个人工作总结
2015/02/10 职场文书
张思德观后感
2015/06/09 职场文书
求职自荐信该如何书写?
2019/06/24 职场文书
python 自动化偷懒的四个实用操作
2021/04/11 Python
解决Goland 同一个package中函数互相调用的问题
2021/05/06 Golang
Nginx虚拟主机的配置步骤过程全解
2022/03/31 Servers
Python&Matlab实现樱花的绘制
2022/04/07 Python
SpringBoot Http远程调用的方法
2022/08/14 Java/Android