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的學習,如有錯誤之處,請大牛見諒指出


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM