Django学习——上传文件

上传文件

form表单上传文件注意事项:
	1.method必须是post
	2.enctype参数修改为multipart/form-data
# 错误1  
	CSRF verification failed. Request aborted.
# 解决错误 
	注释掉 settings.py中的MIDDLEWARE   # 'django.middleware.csrf.CsrfViewMiddleware',
    
def func1(request):
    if request.method == 'POST':
        print(request.POST)  # <QueryDict: {'username': ['jason']}>
        file_obj = request.FILES.get('myfile')
        print(file_obj.name)  # 获取文件名称
        with open(r'%s'%file_obj.name,'wb') as f:
            # for line in file_obj:
            #     f.write(line)
            for chunks in file_obj.chunks():
                f.write(chunks)
    return render(request,'func1.html')
posted @ 2022-04-30 20:47  寻月隐君  阅读(46)  评论(0编辑  收藏  举报