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 合并文件的具体实例
Aug 08 Python
使用Python的urllib2模块处理url和图片的技巧两则
Feb 18 Python
Python基于二分查找实现求整数平方根的方法
May 12 Python
Python搭建APNS苹果推送通知推送服务的相关模块使用指南
Jun 02 Python
Python中字典的浅拷贝与深拷贝用法实例分析
Jan 02 Python
多个应用共存的Django配置方法
May 30 Python
Matplotlib scatter绘制散点图的方法实现
Jan 02 Python
Python实现进度条和时间预估的示例代码
Jun 02 Python
python代码中怎么换行
Jun 17 Python
python中strip(),lstrip(),rstrip()函数的使用讲解
Nov 17 Python
基于Python实现粒子滤波效果
Dec 01 Python
Python机器学习算法之决策树算法的实现与优缺点
May 13 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
如何对PHP程序中的常见漏洞进行攻击(下)
2006/10/09 PHP
php垃圾代码优化操作代码
2010/08/05 PHP
smarty内置函数{loteral}、{ldelim}和{rdelim}用法实例
2015/01/22 PHP
PHP判断FORM表单或URL参数来的数据是否为整数的方法
2016/03/25 PHP
PHP数组的定义、初始化和数组元素的显示实现代码
2016/11/05 PHP
PHP5.0~5.6 各版本兼容性cURL文件上传功能实例分析
2018/05/11 PHP
php 使用expat方式解析xml文件操作示例
2019/11/26 PHP
js判断变量是否未定义的代码
2020/03/28 Javascript
JavaScript程序员应该知道的45个实用技巧
2014/03/04 Javascript
js实现具有高亮显示效果的多级菜单代码
2015/09/01 Javascript
详解 javascript中offsetleft属性的用法
2015/11/11 Javascript
JavaScript对象数组如何按指定属性和排序方向进行排序
2016/06/15 Javascript
原生态js,鼠标按下后,经过了那些单元格的简单实例
2016/08/11 Javascript
使用FileReader API创建Vue文件阅读器组件
2018/04/03 Javascript
layui表格内容溢出的解决方法
2019/09/06 Javascript
浅谈layui里的上传控件问题
2019/09/26 Javascript
微信小程序中的video视频实现 自定义播放按钮、封面图、视频封面上文案
2020/01/02 Javascript
js获取url页面id,也就是最后的数字文件名
2020/09/25 Javascript
PyQt5每天必学之像素图控件QPixmap
2018/04/19 Python
对pandas中时间窗函数rolling的使用详解
2018/11/28 Python
解决python中无法自动补全代码的问题
2018/12/04 Python
Python 图像处理: 生成二维高斯分布蒙版的实例
2019/07/04 Python
python利用openpyxl拆分多个工作表的工作簿的方法
2019/09/27 Python
Django密码存储策略分析
2020/01/09 Python
携程英文网站:Trip.com
2017/02/07 全球购物
企业宣传策划方案
2014/05/29 职场文书
经济管理专业求职信
2014/06/09 职场文书
深入开展党的群众路线教育实践活动心得体会
2014/11/05 职场文书
2014年质量工作总结
2014/11/22 职场文书
2014年为民办实事工作总结
2014/12/20 职场文书
就业导师推荐信范文
2015/03/27 职场文书
2015年人事专员工作总结
2015/04/29 职场文书
原生CSS实现文字无限轮播的通用方法
2021/03/30 HTML / CSS
vue+spring boot实现校验码功能
2021/05/27 Vue.js
nginx内存池源码解析
2021/11/20 Servers
Java线程的6种状态与生命周期
2022/05/11 Java/Android