django 图片上传并显示
程序员文章站
2022-07-15 11:43:01
...
# view.py
def Display(request):
if request.method == "POST":
# 判断request.FILES 是否为空
if request.FILES:
img = request.FILES['pic1']
fname = '%s\\upload\\%s' % (settings.MEDIA_ROOT, img.name)
with open(fname, 'wb') as pic:
for c in img.chunks():
pic.write(c)
return render(request, 'index.html', {'img': img, 'judge': "TRUE")
else:
return render(request, 'index.html', {'judge': "FALSE"})
else:
return render(request, 'index.html', {'judge': "FALSE"})
# html
<div id="show">
{% if judge == "TRUE" %}
<img id="photo" src="/media/upload/{{ img }}">
{% endif %}
<div style="text-align: center">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<a class="file">
<input type="file" name="pic1">选择图片
</a>
<br>
<button class="file" type="submit" name="upload">提交</button>
</form>
</div>
</div>