• 【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)



     
  • 相关阅读:
    sprin AOP
    springDI注解
    Spring学习
    cookie、session、token三者之间的关系
    解决报错:Cannot find module 'webpack-cli/bin/config-yargs'
    Vue全家桶-前端工程化
    Vue全家桶-前端路由
    Vue
    Git
    Ajax
  • 原文地址:https://www.cnblogs.com/wanghong1994/p/16027486.html
Copyright © 2020-2023  润新知