文件上传

文件上传 -- 初版

视图函数

def upload(request):
    if request.method == "GET":
        return render(request,'upload.html',locals())
    elif request.method == "POST":
        user = request.POST.get('user')
        obj = request.FILES.get('file')
        # f = open(obj.name, 'wb')
        f = open(os.path.join('upload',obj.name),'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()
        return render(request,'upload.html',locals())

模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>upload</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="text" name="user">
    <input type="file" name="file">
    <input type="submit" value="submit">
</form>
</body>
</html>

推荐阅读更多精彩内容