1. 程式人生 > 其它 >【Django】 原生上傳檔案,後臺接收檔案

【Django】 原生上傳檔案,後臺接收檔案

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)