Python学习总结:Django【高级篇】(二)

文件上传

前端页面内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <form method="POST" action="/upload/" enctype="multipart/form-data">
        <input type="text" name="user" />
        <input type="file" name="img"/>
        <input type="submit"/>
    </form>
</body>
</html>
View Code

后端程序实现

from django.shortcuts import render
import os


# Create your views here.


def upload(request):
    if request.method == 'POST':                # 判断页面请求的方式
        user = request.POST.get('user')         # 获取页面上传的input内容
        # img = request.POST.get('img')
        img = request.FILES.get('img')          # 获取上传的文件 img 对应html页面上的input框中name=img的信息
        f = open(os.path.join('static/images', img.name), 'wb')     # os.path.join 字符串拼接  wb 二进制写 使用w报错
        for chunk in img.chunks():                                  # img.chunks是整个文件的全部内容,每次上传
            f.write(chunk)
        f.close()

        print(user, img)
        print("http://127.0.0.1:8080/static/images/%s" % img.name)  # 获取文件访问路径
    return render(request, 'upload.html')
View Code

结果检查

 

验证码+session功能实现

 

posted @ 2016-09-25 10:18  每天进步一点点!!!  阅读(117)  评论(0)    收藏  举报