Ajax上传文件/文件预览

方法一:直接上传文件

>>>html
        <form action="/ajax/" method="POST" enctype="multipart/form-data">
            <input type="text" name="user">
            <input type="file" name="files">
            <input type="submit" value="提交">
        </form>
    
>>>views
def ajax(request):
    if request.method == 'GET':
        return render(request,'index.html',locals())
    else:
        user =request.POST.get('user')
        img = request.FILES.get('files')
        print(img.name)
        print(img.size)
        f = open(img.name,'wb')
        for line in img.chunks():
            f.write(line)
        f.close()
        return HttpResponse('ok')

思考:1.如何把难看的上传文件的按钮换成好看的按钮?(覆盖)

   2.form组件上传文件?(可对文件进行验证)

方法二:1.jquery结合 formdata对象上传文件    2. 原生ajax结合 formdata对象上传文件    3.iframe + form 上传文件

>>>html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <div>
        <input type="file" id="img">
        <a class="btn" onclick="AjaxSubmit1()">上传</a>
        <a class="btn" onclick="AjaxSubmit2()">上传</a>
    </div>

    <div>
        <iframe id="iframe" name="ifra" style="display: none"></iframe>
        <form action="/ajax/" method="POST" id="fm" target="ifra" enctype="multipart/form-data">
            <input type="text" name="k1">
            <input type="text" name="k2">
            <input type="file" name="k3">
            <a onclick="AjaxSubmit3()">提交</a>
        </form>
    </div>

<script src="/static/js/jquery-3.3.1.js"></script>
<script>
    
    function AjaxSubmit1() {
        var data = new FormData();
        data.append('k1','v1');
        data.append('k2','v2');
        data.append('k3',document.getElementById('img').files[0]);
        $.ajax({
            url:'/ajax/',
            type:'POST',
            data:data,
            success:function (arg) {
                console.log(arg)
            },
            processData:false,
            contentType:false
        })
    }
    
    function AjaxSubmit2() {
        var data = new FormData();
        data.append('k1','v1');
        data.append('k2','v2');
        data.append('k3',document.getElementById('img').files[0]);
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
             if(xhr.readyState == 4){
                console.log(xhr.responseText);
             }
        };
        xhr.open('POST','/ajax/');
        xhr.send(data);
    }

    function AjaxSubmit3() {
        document.getElementById('iframe').onload = reload1;
        document.getElementById('fm').submit()
    }

    function reload1() {
        var content = this.contentWindow.document.body.innerHTML;
        var obj =JSON.parse(content);
        console.log(obj)
    }

</script>

</body>
</html>

>>>views

def ajax(request):
    print(request.POST)
    print(request.GET)
    print(request.FILES)
    ret = {'status':True,'message':'....'}
    import json
    return HttpResponse(json.dumps(ret))

 文件预览:

>>>html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <iframe id="iframe" name="ifra" style="display: none"></iframe>
        <form action="/ajax/" method="POST" id="fm" target="ifra" enctype="multipart/form-data">
            <input type="file" name="k3" onchange="uploadfile()">
        </form>
    </div>
    <h3>预览</h3>
    <div>

        <div id="preval"></div>

    </div>

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

    function uploadfile() {
        document.getElementById('iframe').onload = reload;
        document.getElementById('fm').submit()
    }

    function reload() {
        var content = this.contentWindow.document.body.innerHTML;
        var obj =JSON.parse(content);
        var tag = document.createElement('img');
        tag.src = "/"+obj.data;
        $("#preval").empty().append(tag);
    }

</script>

</body>
</html>

>>>views
import json
import os
import uuid
def ajax(request):
    nid = str(uuid.uuid4())
    ret = {'status':True,'data':None,'message':None}
    obj = request.FILES.get('k3')
    file_path = os.path.join('static',nid+obj.name)
    f = open(file_path,'wb')
    for line in obj.chunks():
        f.write(line)
    f.close()
    ret['data']= file_path
    return HttpResponse(json.dumps(ret))
原文地址:https://www.cnblogs.com/yzcstart/p/10741518.html