开发实践7_project

要求:

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

结果:

开发实践7_project_第1张图片开发实践7_project_第2张图片(图片 网页来源 无水印 不能明确出处)

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//", 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 %}


    
    show_img


No such img.

你可能感兴趣的:(java,前端,javascript)