day21

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了day21相关的知识,希望对你有一定的参考价值。

一、课上内容

1、文件上传
a. html Form表单提交
b. Ajax提交
原生XMLHttpRequest
http://www.cnblogs.com/wupeiqi/articles/5703697.html

XmlHttpReqeust() 类
xhr = XmlHttpReqeust()
xhr.send("k1=v1;k2=v2")


jQuery Ajax
$.ajax({}) 内部调用XmlHttpReqeust来发送的Ajax

$.ajax({
data: {\'k1\': \'v1\', \'k2\': \'v2\'}
})

2、验证码 + session


抽屉:
需求分析
数据库设计
- 用户表
- 短信、邮件临时表
- 新闻类型表:
1 42区
2 段子
3 兔皮纳
4 挨踢
5 你问我答
- 新闻表:
标题,摘要,url,赞数1

http://dajia.qq.com/original/oldtimes/csc20160925.html
图片路径(url),摘要
/detail/1

标题:asdf
摘要:asdfasd
URL:http://dajia.qq.com/original/oldtimes/csc20160925.html
类型:1

标题:
摘要:asdfasd
URL:http://dajia.qq.com/original/oldtimes/csc20160925.html
类型:2

- 点赞表
新闻ID 用户ID
1 1

- 评论表
新闻ID 用户ID 评论内容 评论事件 顶 踩

 

二、实例

目录结构

 1.上传文件

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r\'^admin/\', admin.site.urls),
    url(r\'^upload/\', views.upload),
    url(r\'^ajax/\', views.ajax),
    url(r\'^xhr_ajax\', views.xhr_ajax),
]

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
      <iframe id="my_iframe" name="my_iframe" style="display: none" src=""></iframe>
      <form method="POST" action="/upload/" enctype="multipart/form-data">
          <input type="text" id="user" name="user" />
          <input type="file" id="img" name="img" onchange="uploadfile3();" />
          <input type="submit" />
      </form>
      <div id="container">

      </div>
{#      <a onclick="uploadfile();">XMLHttpRequset上传</a>#}
      <a onclick="uploadfile2();">Jquery_XMLHttpRequset上传</a>

<script src="/static/jquery-1.9.1.min.js"></script>
<script>
    function uploadfile(){

        var form = new FormData();
        form.append(\'user\',document.getElementById(\'user\').value);

        var fileobj = document.getElementById(\'img\').files[0];
        form.append(\'img\', fileobj);

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){

                var data = xhr.responseText;
                console.log(data);
            }
        };

        xhr.open(\'post\',\'/upload/\', true);
        xhr.send(form);

    }


    function uploadfile2(){
        var fileObj = $("#img")[0].files[0];
        var form = new FormData();
        form.append(\'img\', fileObj);
        form.append(\'user\',\'alex\');

        $.ajax({
            type: \'POST\',
            url: \'/upload/\',
            data: form,
            processData: false,
            contentType: false,
            success: function(arg){
                console.log(arg);
            }
        })
    }


    function uploadfile3(){
        $("#container").find(\'img\').remove();
        //绑定事件callback
        document.getElementById(\'my_iframe\').onload = callback;
        document.getElementById(\'fo\').target = \'my_iframe\';
        document.getElementById(\'fo\').submit();
    }

    function callback(){
        var text = $(\'#my_iframe\').contents().find(\'body\').text();
        //反序列化
        var json_data = JSON.parse(text);
        console.log(json_data);

        if(json_data.status){
            var tag = document.createElement(\'img\');
            tag.src = "/" + json_data.data;
            tag.className = \'img\';
            $(\'#container\').append(tag);
        }else{
            alert(json_data.error);
        }

    }
</script>
</body>
</html>

views.py

from django.shortcuts import render,HttpResponse
import  os

import  json
def upload(request):
    if request.method == \'POST\':
        ret = {\'status\': False, \'data\':None,\'error\':None}
        try:
            user = request.POST.get(\'user\')
            #这里获取的是文件名不是文件
            # img = request.POST.get(\'img\')
            #这里获取的是文件 对象类型
            img = request.FILES.get(\'img\')
            file_path = os.path.join(\'static\',img.name)
            f = open(file_path,\'wb\')
            print(img.name,type(img))
            for chunk in img.chunks():
                f.write(chunk)
            f.close()
            ret[\'status\'] = True
            ret[\'data\'] = file_path

        except Exception as e:
            ret[\'error\'] = str(e)

        return HttpResponse(json.dumps(ret))

    return render(request,\'upload.html\')

效果

 

  




以上是关于day21的主要内容,如果未能解决你的问题,请参考以下文章

day06-jsp

day21模块

LeetCode刷题笔记-数据结构-day21

LeetCode刷题笔记-数据结构-day21

LeetCode刷题笔记-数据结构-day21

Day21