Django #上传文件

###

views.py

from django.shortcuts import render,HttpResponse,redirect
import os
# Create your views here.



def login(request):
    # return HttpResponse('login successful!')
    if request.method == 'GET':
        return render(request,'login.html')

    elif request.method == 'POST':

        v = request.FILES.get('fafafa')
        f = open(os.path.join('upload',v.name),'wb')
        for i in v.chunks():
            f.write(i)
        f.close()
        return render(request,'login.html')

###

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login/" method="POST" enctype="multipart/form-data">
        <p>
            <input type="text" name="user" placeholder="用户名"/>
        </p>
        <p>
            <input type="password" name="pwd" placeholder="密码"/>
        </p>
            <input type="submit" value="登录"/>
        <p>
        <input type="file" name="fafafa"/>
        </p>
    </form>
</body>
</html>

###

原文地址:https://www.cnblogs.com/lwsup/p/7476576.html