Django - 上传文件

概述

  • 当 Django 在处理文件上传的时候,文件数据被保存在 request.FILES
  • FILES 的每个键为下边代码中的 name 属性的值
    1
    <input type="file" name="" />
  • FILES 只有在请求的方式为 POST 且提交的 form 带有 enctype="multipart/form-data" 的情况下才会包含数据。否则,FILES 将为一个空的类似字典的对象

存储路径

  • static 目录下创建名为 media 的目录

    1
    2
    # 配置上传路径
    MEDIA_ROOT = os.path.join(BASE_DIR, "static\media")

上传页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<form action="/upfile/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file">
<hr>
<input type="file" name="file">
<hr>
<input type="file" name="pic">
<hr>
<input type="submit" value="上传">
</form>
</body>
</html>

视图代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
from django.conf import settings


def upfile(request):
if request.method == "GET":
return render(request, 'myApp/upfile.html')
else:
response = HttpResponse()

for key in request.FILES:
for file in request.FILES.getlist(key):
fileName = os.path.splitext(file.name)[1][1:]
allowFile = ["jpg", "png", "jpeg", "gif"]
if fileName not in allowFile:
response.write(file.name + "不符合规则")
else:
upfilePath = os.path.join(settings.MEDIA_ROOT, file.name)
with open(upfilePath, "wb") as fp:
for c in file.chunks():
fp.write(c)
response.write(file.name + "上传成功")
return response
------------- 本文结束 感谢您的阅读 -------------
正在加载今日诗词....