要求:
表单类,上传img到服务器某路径,再显示在网页。
结果:


(图片 网页来源 无水印 不能明确出处)
upload_app form.py //
class UploadForm(forms.Form):
img = forms.ImageField(label="img")
setting //
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'upload_files'), # 'static' # 即 ./static
]
MEDIA_ROOT = os.path.join(BASE_DIR, "upload_files")
sub urls //
path("upimg/", upimg, name='upimg'),
path("upimg/showimg/<path:apath>/", showimg, name='img'),
views //
def upimg(request):
if request.method == "GET":
form = UploadForm()
return render(request, "upimg.html", locals())
if request.method == "POST":
img = request.FILES.get("img")
file_name = img.name
#file_path = 'D:/webDevelopment/exercises/djangoProject/upload_files/' + file_name
file_path = os.path.join(BASE_DIR, "upload_files", file_name)
with open(file_path, "wb") as f:
for chunk in img.chunks():
f.write(chunk)
return redirect(reverse('upload:img', args=(file_name, )))
def showimg(request, apath):
print(apath)
return render(request, "img.html", locals())
template //
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>show_img</title>
</head>
<body>
<img src="{% static apath %}" alt="No such img.">
</body>

















![【C++入门到精通】智能指针 auto_ptr、unique_ptr简介及C++模拟实现 [ C++入门 ]](https://img-blog.csdnimg.cn/direct/ad0cc2887ce140ed8f11e8276788b498.png#pic_center)

