Django 图片上传及保存

Django学习第七天

今天在练习Django项目时需要用户上传图片。于是先制作了一个简陋的页面用于用户提交信息。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/user/register" method="POST">
    {% csrf_token %}
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="pwd"><br>
    电话:<input type="number" name="phone"><br>
    邮箱:<input type="text" name="e_mail"><br>
    头像:<input type="file" name="photo"><br>
    <input type="submit">
</form>
</body>
</html>

user/views.py
接收上传的数据

def register(request):
    print(request.POST)#测试接收post传过来的数据
    print(request.FILES)#测试接收上传文件
    return render(request,'register.html')

接收结果
在这里插入图片描述
可以清楚的看到request.FILES并没有接收到任何值。
这需要在网页表单端加上enctype=“multipart/form-data”
如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/user/register" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="pwd"><br>
    电话:<input type="number" name="phone"><br>
    邮箱:<input type="text" name="e_mail"><br>
    头像:<input type="file" name="photo"><br>
    <input type="submit">
</form>
</body>
</html>

再次测试如图:
在这里插入图片描述

图片保存

def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        username = request.POST['username']
        password = request.POST['pwd']
        phone = request.POST['phone']
        e_mail = request.POST['e_mail']
        file_obj = request.FILES.get('photo')
        # print(username,password,phone,e_mail)
        file_name = './static/img/'+username+'_'+str(int(time.time()))+'.'+file_obj.name.split('.')[-1]#构造文件名以及文件路径
        if file_obj.name.split('.')[-1] not in ['jpeg','jpg','png']:
            return HttpResponse('输入文件有误')
        try:
            user = UserInfo()
            user.username = username
            user.phone = phone
            user.password = password
            user.e_mail = e_mail
            user.Image = file_name[1:]
            user.save()
            with open(file_name,'wb+') as f:
                f.write(file_obj.read())
        except Exception as e:
            print(e)
        return HttpResponse('OK')

showuser.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        img{
            width: 100px;
            height: 100px;
            border-radius: 50%;
        }
    </style>
</head>
<body>
{% for i in user %}
    <p>{{ i.username }}</p>
    <p>{{ i.phone }}</p>
    <p>{{ i.e_mail }}</p>
    <img src="{{ i.Image }}">
    <br>
{% endfor %}
</body>
</html>

页面展示效果:
Django 图片上传及保存_第1张图片
笔者目前才刚刚开始django的学习,如有错误之处,请大牛见谅指出

你可能感兴趣的:(Django学习日志)