前段:
Title
{% csrf_token %}
输入正确
ajax上传文件(前段):
{% load static %}
Title
{% csrf_token %}
{#
#}
输入正确
头像:
后端:
def upload(request):
# name = request.POST()
# return HttpResponse('ok')
if request.method == 'GET':
return render(request, 'upload.html')
else:
file_obj = request.FILES.get('file_obj')
# 这里的file_obj拿到了文件的对象,这个对象包含了文件的名字,二进制内容
# print(file_obj, type(file_obj))
file_name = file_obj.name
import os
file_path = os.path.join(settings.BASE_DIR, 'static2', 'img', file_obj.name)
# 这里file_path是存储文件的路径
# print(settings.BASE_DIR)
with open(file_path, 'wb') as f:
for chunk in file_obj.chunks():
f.write(chunk)
return HttpResponse('ok')
settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'statics'),
os.path.join(BASE_DIR, 'static2'),
]