HTML:
url.py:
url('task/post/$', add_task.AddTask.as_view()),
add_task.py:
import os
import random
from rest_framework.views import APIView
from django.shortcuts import render,redirect,HttpResponse
from dal import models
from django.http import JsonResponse
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def referralID():
str = ""
for i in range(6):
code = random.randrange(3)
if code == 0:
# 随机生成一个大写字母
ch = chr(random.randrange(ord("A"), ord("Z") + 1))
str += ch
elif code == 1:
# 随机生成一个小写字母
ch = chr(random.randrange(ord("a"), ord("z") + 1))
str += ch
elif code == 2:
# 随机生成一个数字
ch = chr(random.randrange(ord("0"), ord("9") + 1))
str += ch
return str
class AddTask(APIView):
def post(self,request):
username = str(request.data.get("username"))
task_title = str(request.data.get("title"))
text = str(request.data.get("text"))
file = request.FILES.get('file',None)
# 加密文件名(完整的文件路径)
row_name = file.name.split(".")[0] + referralID()
md5_name = row_name + "." + file.name.split(".")[1]
# 上传图片
with open(BASE_DIR + "\\media\\file\\" + md5_name, 'wb') as f:
for chunk in file.chunks():
f.write(chunk)
# 数据库路径
sql_path = "file\\{}".format(md5_name)
user_id = models.UserInfo.objects.get(username=username).pk
message = {}
try:
models.Tasks.objects.create(task_title=task_title,student_text=text,student_file=sql_path,user_id=user_id)
message['code'] = 200
message['message'] = "提交成功"
return JsonResponse(message)
except Exception as e:
print(e)
message['code'] = 444
message['message'] = "提交失败"
return JsonResponse(message)