#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import traceback from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic.base import View from Ansjer.config import BASE_DIR from Object.ResponseObject import ResponseObject from Object.TokenObject import TokenObject class FAQUploadView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(FAQUploadView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): request.encoding = 'utf-8' request_dict = request.GET fileName = request.FILES.get('fileName', None) return self.validate(fileName, request_dict) def post(self, request, *args, **kwargs): request.encoding = 'utf-8' request_dict = request.POST fileName = request.FILES.get('fileName', None) return self.validate(fileName, request_dict) def validate(self, fileName, request_dict): token = TokenObject(request_dict.get('token', None)) response = ResponseObject() if token.code != 0: return response.json(token.code) try: path = '/'.join((BASE_DIR, 'static/FAQImages')).replace('\\', '/') + '/' if not os.path.exists(path): os.makedirs(path) file_name = path + str(fileName) if os.path.exists(file_name): os.remove(file_name) destination = open(file_name, 'wb+') for chunk in fileName.chunks(): destination.write(chunk) destination.close() else: file_name = path + str(fileName) if os.path.exists(file_name): os.remove(file_name) destination = open(file_name, 'wb+') for chunk in fileName.chunks(): destination.write(chunk) destination.close() except Exception as e: errorInfo = traceback.format_exc() print('上传文件错误: %s' % errorInfo) return response.json(700, {'details': repr(e)}) else: index = file_name.find('static/') filePath = file_name[index:] return response.json(0, {'filePath': filePath}) class FAQView(View): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super(FAQView, self).dispatch(*args, **kwargs) def post(self, request, *args, **kwargs): request.encoding = 'utf-8' request_dict = request.POST operation = kwargs.get('operation', None) return self.validate(request_dict, operation) def get(self, request, *args, **kwargs): request.encoding = 'utf-8' request_dict = request.GET operation = kwargs.get('operation', None) return self.validate(request_dict, operation) def validate(self, request_dict, operation): return