ElementUI上传⽂件以及限制⼀、概述
现有项⽬中,涉及⽂件上传。要求:
1. ⽂件必须是excel
2. 只能上传1个⽂件
3. ⽂件⼤⼩不能超过5M
⼆、Upload 上传
注意:ElementUI Upload 上传,需要和后端api结合才能使⽤。
演⽰环境使⽤django,版本为:3.1.5
新建django项⽬
新建django项⽬,项⽬名为upload_demo,app名为api
安装以下模块
Django==3.1.5
djangorestframework==3.11.1
django-cors-headers==3.5.0
以上是我环境的版本,这⾥不做强制要求,安装最新版本即可。
注意:django-cors-headers是⽤来解决跨域问题的。
修改upload_demo/settings.py
注册app
INSTALLED_APPS = [
'ib.admin',
'ib.auth',
'ttypes',
'ib.sessions',
'ssages',
'ib.staticfiles',
'api.apps.ApiConfig',
'rest_framework',
'corsheaders', # 注册应⽤cors
]
中间件增加
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'ib.sessions.middleware.SessionMiddleware', 'django.middlewaremon.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'ib.auth.middleware.AuthenticationMiddleware', 'ssages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', # 注册组件cors ]
最后⼀⾏增加
#跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
# CORS_ORIGIN_WHITELIST = (
# '',
# )
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
vue element admin'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)
修改api/views.py,增加视图函数
from rest_framework.views import APIView
from upload_demo import settings
from django.shortcuts import render, redirect, HttpResponse from django.http import JsonResponse
from rest_framework import status
import os
import uuid
class File(APIView):
def post(self, request):
print(request.FILES)
# 接收⽂件
file_obj = ('file', None)
print("file_obj", file_obj.name)
# 判断是否存在⽂件夹
head_path = os.path.join(settings.BASE_DIR,'upload')
print("head_path", head_path)
# 如果没有就创建⽂件路径
if not ists(head_path):
os.makedirs(head_path)
# 判断⽂件⼤⼩不能超过5M
if file_obj.size > 5242880:
return JsonResponse({'status': status.HTTP_403_FORBIDDEN, 'msg': '⽂件过⼤'},
status=status.HTTP_403_FORBIDDEN)
# ⽂件后缀
suffix = file_obj.name.split(".").pop()
print("⽂件后缀", suffix) # 图⽚后缀 png
# 判断⽂件后缀
suffix_list = ["xlsx","xls"]
if suffix not in suffix_list:
return JsonResponse({'status': status.HTTP_403_FORBIDDEN, 'msg': '只能选择excel⽂件'}, status=status.HTTP_403_FORBIDDEN)
# 重命名⽂件名
file_name = '%s.%s'%(uuid.uuid4(),suffix)
print("file_name",file_name)
# 储存路径
file_path = os.path.join(head_path,file_name)
print("储存路径", file_path)
# 写⼊⽂件到指定路径
with open(file_path, 'wb') as f:
for chunk in file_obj.chunks():
f.write(chunk)
data = {}
data['name'] = file_name
return JsonResponse({'status': status.HTTP_200_OK, 'data': data}, status=status.HTTP_200_OK) View Code
修改upload_demo/urls.py
ib import admin
from django.urls import path
from api import views
urlpatterns = [
path('admin/', admin.site.urls),
path('file/excel_upload/',views.File.as_view())
]
启动django项⽬,访问链接为:127.0.0.1:8000/
新建vue测试页
安装axios
npm install axios --save
test.vue
<template>
<div >
<el-upload ref="upload"
class="upload-demo" :multiple='false' :auto-upload='true' list-type='text' :show-file-list='true'
:before-upload="beforeUpload" :before-remove="beforeRemove" :drag='true' action='' :limit="1" :on-exceed="handleExceed" :http-request="uploadFile" accept=".xlsx">
<i class="el-icon-upload"></i>
<div class="el-upload__text"><em>点击上传,仅限excel⽂件</em></div>
<!-- <div class="el-upload__tip" slot="tip">仅限excel⽂件</div>-->
</el-upload>
<el-button type="primary" @click="onSubumit">提交</el-button>
</div>
</template>
<script>
// 导⼊模块
import axios from 'axios'
export default {
components: {
axios
},
data() {
return {
isUpload:false, // 是否上传⽂件
}
},
mounted: function() {
},
methods: {
// 上传⽂件之前的钩⼦
beforeUpload(file) {
//判断⽂件格式
let hz = file.name.split('.').pop()
// console.log("hz",hz)
if (hz != 'xlsx' && hz != 'xls') {
this.$(`只能选择excel⽂件`)
return false
}
// 判断⽂件⼤⼩
let fileSize = file.size / 1024 / 1024 < 5
if (!fileSize) {
this.$('上传⽂件⼤⼩不能超过 5MB')
return false
}
this.isUpload = true
},
// 删除⽂件之前的钩⼦
beforeRemove(file){
this.isUpload = false
},
// 上传⽂件个数超过定义的数量
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个⽂件,请删除后继续上传`)
},
// 上传⽂件
uploadFile(item) {
let _this = this
let fileObj = item.file
const form = new FormData()// FormData 对象
form.append('file', fileObj)// ⽂件对象 'upload'是后台接收的参数名 axios({
url: '127.0.0.1:8000/file/excel_upload/',
data: form,
method: 'POST',
contentType: 'multipart/form-data',
processData: false//告诉jquery不要对form进⾏处理
// contentType: false, //指定为false才能形成正确的Content-Type })
.then(function(res) {
// console.log('上传成功', res)
// console.log("上传路径",l_file_path)
_this.$message.success("上传成功")
})
.catch(function(err) {
let res = sponse
// console.log('失败', res)
_this.$(res.data.msg)
})
},
// 检查是否上传
onSubumit(){
if (this.isUpload == false){
this.$("请上传excel⽂件")
return false
} else {
this.$message.success("⽂件已上传")
return true
}
},
}
}
</script>
<style>
</style>
View Code
请⾃⾏修改路由
访问vue测试页,效果如下:
上传⾮excel⽂件,效果如下:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论