现有项目中,涉及文件上传。要求:

1. 文件必须是excel

2. 只能上传1个文件

3. 文件大小不能超过5M 

 

二、Upload 上传

注意:ElementUI Upload 上传,需要和后端api结合才能使用。

演示环境使用django,版本为:3.1.5

 

新建django项目

新建django项目,项目名为upload_demo,app名为api

ElementUI 上传文件以及限制

 安装以下模块

Django==3.1.5
djangorestframework==3.11.1
django-cors-headers==3.5.0

以上是我环境的版本,这里不做强制要求,安装最新版本即可。

注意:django-cors-headers是用来解决跨域问题的。

 

修改upload_demo/settings.py

注册app

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api.apps.ApiConfig',
    'rest_framework',
    'corsheaders',  # 注册应用cors
]

 

中间件增加

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware', # 注册组件cors
]

 

最后一行增加

#跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
# CORS_ORIGIN_WHITELIST = (
#     'http://',
# )

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    '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 = request.FILES.get('file', None)
        print("file_obj", file_obj.name)

        # 判断是否存在文件夹
        head_path = os.path.join(settings.BASE_DIR,'upload')
        print("head_path", head_path)
        # 如果没有就创建文件路径
        if not os.path.exists(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

相关文章:

  • 2021-10-16
  • 2021-08-12
  • 2022-02-15
  • 2022-12-23
  • 2022-12-23
  • 2021-06-27
  • 2021-11-24
猜你喜欢
  • 2022-12-23
  • 2021-11-11
  • 2022-12-23
  • 2022-12-23
  • 2021-10-16
  • 2021-11-20
  • 2021-10-16
相关资源
相似解决方案