相关配置
实现文件上传功能时,首先需要注意以下几点:
- 前端表单
表单需要设置enctype="multipart/form-data"且提交类型为POST
- settings.py中配置文件存储的路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/upload')
前端表单
<form action="{% url 'App01:upload' %}" method="post" enctype="multipart/form-data">
{
% csrf_token %}
<input type="file" name="photo">
<input type="submit" value="upload">
</form>
后端实现
- 不封装文件上传类
def file_upload(request):
if request.method == 'POST':
# 获取文件上传对象
file_obj = request.FILES.get('photo')
# 添加文件后才能提交上传
if file_obj:
# 文件存储路径
file_path = os.path.join(MEDIA_ROOT, file_obj.name)
try:
with open(file_path, 'wb') as fp:
# multiple_chunks方法用于判断⽂件是否⼤于2.5M
if file_obj.multiple_chunks():
# 文件按块写入
for chip in file_obj.chunk()