文件上传

form表单实现文件上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bs/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-offset-3 col-md-6">
            <form action="" style="margin-top:100px" class="form-group" method="post" enctype="multipart/form-data">
                {% csrf_token  %}
                <div class="form-group">
                    <label>用户名:</label>
                    <input type="text" name="user" class="form-control">
                </div>
                <div>
                    <label>上传文件</label>
                    <input type="file" name="file_obj">
                </div>
                <input type="submit" class="btn btn-info" value="提交">
            </form>
        </div>
    </div>
</div>

</body>
<script src="/static/jquery/jquery-3.3.1.js"></script>
</html>

django部分

def upload(request):
    if request.POST:
        file_obj = request.FILES.get("file_obj")
        print(file_obj)
        path = os.path.join(settings.MEDIA_ROOT, file_obj.name)
        
        with open(path, 'wb')as f:
            for line in file_obj:
                f.write(line)
    return render(request, "upload.html")

ajax实现文件上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <link rel="stylesheet" href="/static/bs/css/bootstrap.css">

    <style type="text/css">
        .error {
            color: #ff2b23;
        }
    </style>
</head>

<body>
<div class="container" style="margin-top: 100px">
    <div class="row">
        <div class="col-md-offset-3 col-md-6">
            <form id="form">
                {% csrf_token %}
                <div class="form-group">
                    <label>用户名:</label>
                    <input type="text" class="form-control" id="user" name="user">
                    <span class="error pull-right"></span>
                </div>
                <div class="form-group">
                    <label>密码:</label>
                    <input type="password" class="form-control" id="pwd" name="pwd">
                    <span class="error pull-right"></span>
                </div>
                <div class="form-group">
                    <label>确认密码:</label>
                    <input type="password" class="form-control" id="re_pwd" name="re_pwd">
                    <span class="error pull-right"></span>
                </div>
                <div class="form-group">
                    <label for="avatar">头像
                        <img id="avatar_img" src="/media/avatar/default.jpeg" height="60" width="60">
                    </label>
                    <input type="file" id="avatar" name="avatar" style="display: none;">
                </div>
                <input type="button" class="sub btn btn-info" value="注册">
            </form>
        </div>
    </div>
</div>
</body>
<script src="/static/jquery/jquery-3.3.1.js"></script>
<script type="text/javascript">
    $("#avatar").change(function () {
        var file_obj = $(this)[0].files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file_obj);
        console.log(reader.result);
        reader.onload = function () {
            $("#avatar_img").attr("src", reader.result);
        }

    });
    $(".sub").click(function () {
        var pwd = $("#pwd").val();
        var re_pwd = $("#re_pwd").val();

        if (pwd != re_pwd) {
            $("#re_pwd+ span").html("两次密码不一致");
            setTimeout(function () {
                $("#re_pwd").next().html('');
            }, 1000);
            return
        }


        var formdata = new FormData();
        var requestData = $("#form").serializeArray();
        $.each(requestData, function (index, data) {
            formdata.append(data.name, data.value)
        });
        console.log(formdata);
        $.ajax({
            url: "",
            type: "post",
            contentType: false,
            processData: false,
            data: formdata,
            success: function (data) {
                console.log(data);
                if (data.user) {
                    alert("注册成功!");
                    location.href = "/login/";
                } else {
                    $("span.error").html('');
                    $.each(data.msg, function (field, error_list) {
                        console.log(field);
                        console.log(error_list);
                        $("#" + field).next().html(error_list);
                    })
                }
            }

        })


    })
</script>
</html>
django部分

views.py

def reg(request):
    print(request.POST)
    if request.is_ajax():
        form = UserForm(request.POST)
        response = {"user": None, "msg": None}
        if form.is_valid():
            user = form.cleaned_data.get('user')
            pwd = form.cleaned_data.get('pwd')
            avartar_obj = request.FILES.get('avatar')
            extra = {}
            if avartar_obj:
                extra["avatar"] = avartar_obj
            models.UserInfo.objects.create_user(username=user, password=pwd, **extra)
            response["user"] = user
            
        else:
            print(form.errors)
            response["msg"] = form.errors
        return JsonResponse(response)
    return render(request, 'reg.html')
    
def login(request):
    if request.is_ajax():
        response = {"user": None, "msg": None}
        print(request.POST)
        username = request.POST.get("user")
        pwd = request.POST.get("pwd")
        user = auth.authenticate(username=username, password=pwd)
        
        if user:
            auth.login(request, user)
            response["user"] = user.username
        else:
            response["msg"] = "用户名或者密码不正确"
        return JsonResponse(response)
    
    return render(request, "login.html")

models

class UserInfo(AbstractUser):
    avatar = models.FileField("avatar/", default='avatar/default.jpeg')
posted @ 2018-07-27 00:01  Jason_lincoln  阅读(114)  评论(0编辑  收藏  举报