Template中 注意要设置with-credentials为true
<el-upload
class="upload-demo"
action='${SITE_URL}file_upload/'
:headers='headers'
:limit="1"
:with-credentials='true'>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
JS
//data中
headers: {},
//mounted中
this.headers['X-CSRFToken'] = getToken()
static/css/index.css 中添加一行代码 因为会被其他样式给覆盖了
.el-upload__input {
display: none !important;
}
Python
# 上传文件接口
from django.shortcuts import HttpResponse
from django.utils.encoding import escape_uri_path
import time
import os
def file_upload(request):
obj = request.FILES.get('file')
t = time.strftime('%Y%m%d%H%M%S')
name = t + '$' + obj.name.split('.')[0] + '.' + obj.name.split('.')[1]
name = name.replace(" ", '')
# 判断是否存在上传路径文件夹 不存在创建文件夹
if os.path.exists('uploads') == False:
os.mkdir('uploads')
path = os.path.join('uploads',name)
f = open(path,'wb')
for line in obj.chunks():
f.write(line)
f.close()
return render_json({'result': True, 'data': {'upPath': path}})
网友评论