django_上传文件

要求:  写一个文件上传:如果文件名字重复,不要覆盖,并且放到项目根路径的media文件夹下

def upload(request):
    if request.method == "GET":
        return render(request,'upload.html')

    if request.method == "POST":
        myfile = request.FILES.get('myfile')
        name = myfile.name
        
        import os
        from JsonResponse.settings import BASE_DIR
        path = os.path.join(BASE_DIR,'media')
        file_path = os.path.join(path,name)                 #将文件放在media文件夹下

        import uuid

        if os.path.exists(file_path):                        #如果文件存在,生成随机前缀名
            end_name = os.path.splitext(name)[-1][1:]        #获取文件后缀名
            name = ('%s.%s') % (str(uuid.uuid4()), end_name) 

            file_path = os.path.join(path, name)
        with open(file_path,'wb') as f:
            for line in myfile:
                f.write(line)
        return HttpResponse('上传完毕!!!!')
原文地址:https://www.cnblogs.com/zhaijihai/p/9931629.html