from rest_framework.parsers import MultiPartParser
from rest_framework.decorators import parser_classes
from django.views.decorators.csrf import csrf_exempt#不进行csrf验证
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
@api_view(['POST'])
@csrf_exempt
@parser_classes((MultiPartParser,))#参数类型
@authentication_classes((TokenAuthentication, SessionAuthentication))
@permission_classes((IsAuthenticated,))
def upload_file(request):
# 存储路径
mk_path = 'path/'
# 判断目录是否已经存在
mk_path_exist = Path(mk_path)
# 存在时,删除目录下的相应文件
if mk_path_exist.is_dir():
file_list = os.listdir(mk_path)
for f in file_list:
if filename in f:
os.remove(os.path.join(mk_path, f))
else:
# 创建目录
os.mkdir(mk_path)
# 获取上传的文件
file_obj = request.FILES.get('file', None)
# 文件保存的位置
filename = 'path/aaa.xls'
# 打开文件,没有新增
destination = open(filename, 'wb+')
for chunk in file_obj.chunks():
destination.write(chunk)
destination.close()
return Response({'code': '200', 'message': 'OK'})