1:导入element
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 %}
更新社团封面
{% comment %} 上传文件之前的钩子,参数为上传的文件 {% endcomment %}
{% comment %} 上传图片 {% endcomment %}
# JS:
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'x89PNGrnx1anx00x00x00rIHDRx00x0
#
# 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:UsersuserDesktopDownTestmediausernameheadhead.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组件完成一个上传文件的功能。但是不知道是不是因为我没有发现,我翻遍了官网都没有找到这个组件点击上传以后发的是什么样的数据请求。
终于我好像突然想起来浏览器的开发者工具可以查看发出的请求
于是我们可以写这么一个组件来一探究竟:
点击上传到服务器以后前台就会发出请求,我们就可以使用devtool看具体的请求头等等数据,具体位置在这里:
点击这个upload,找一找,我们就会发现最下面有一个file
这应该就是我们要上传的文件。可以看见它是以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文件上传方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。



