使用ajax发送文件的三种方式及预览图片的方法,上传按钮美化

后端代码

def upload(request):
    if request.method == "GET":
        return render(request,'upload.html')
    if request.method =="POST":
        pass

def upload_file(request):
    request.POST.get('username')
    fafafa = request.FILES.get('fileobj')
    img_path = os.path.join('static/img/',fafafa.name)
    with open( img_path, 'wb') as f:
        for item in fafafa.chunks():
            f.write(item)
    ret = {'code':True,'data':img_path}
    return HttpResponse(json.dumps(ret))
views.py

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            position: relative;
            width: 100px;
            height: 30px;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .c2 {
            position: absolute;
            width: 100px;
            height: 30px;
            z-index: 10;
            opacity: 0;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
        }

        .c3 {
            display: inline-block;
            background-color: blue;
            color: white;
            z-index: 9;
            position: absolute;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
        }
    </style>
</head>
<body>
<div class="c1">
    <input class="c2" type="file" id="file11" name="file1"/>
    <a class="c3">上传</a>
</div>
<h3>原生XMLHttpRequest提交</h3>
<input type="button" value="XML提交" onclick="xhrSunbmit();">
<h3>jquery提交</h3>
<input type="button" value="jquery提交" onclick="jqSunbmit();">
<hr/>
<hr/>
<h3>iframe提交</h3>
    <form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
        {% csrf_token %}
        <iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
        <input type="file" name="fileobj" onchange="changeUpalod();" />
{#        <input type="submit" onclick="iframeSubmit();" value="Form提交"/>#}
    </form>
<div id="preview"></div>
<script src="/static/jquery.js"></script>
<script src="/static/jquery.cookie.js"></script>
<script>

    function xhrSunbmit() {
        var file_obj = document.getElementById('file11').files[0];
        var fd = new FormData();
        fd.append('username', 'root');
        fd.append('fileobj', file_obj);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/upload_file/', true);
        xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var obj = JSON.parse(xhr.responseText);
                console.log(obj);
            }
        };
        xhr.send(fd);
    }

    function jqSunbmit() {
        var file_obj = document.getElementById('file11').files[0];
        var fd = new FormData();
        fd.append('username', 'root');
        fd.append('fafafa', file_obj);
        $.ajax({
            url: '/upload_file/',
            type: 'POST',
            headers: {'X-CSRFtoken': $.cookie('csrftoken')},
            data: fd,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: function (arg, a1, a2) {
                console.log(arg);
                console.log(a1);
                console.log(a2);
            }
        })
    }
    function changeUpalod(){
            $('#ifm1').load(function(){
                var text = $('#ifm1').contents().find('body').text();
                var obj = JSON.parse(text);

                $('#preview').empty();
                var imgTag = document.createElement('img');
                imgTag.src = "/" + obj.data;
                $('#preview').append(imgTag);
            });
            $('#form1').submit();
        }

 /*   function iframeSubmit(){
            $('#ifm1').load(function(){
                var text = $('#ifm1').contents().find('body').text();
                var obj = JSON.parse(text);

                $('#preview').empty();
                var imgTag = document.createElement('img');
                imgTag.src = "/" + obj.data;
                $('#preview').append(imgTag);
            })
        }*/
</script>
</body>
</html>
upload.html

猜你喜欢

转载自www.cnblogs.com/qiangayz/p/9022533.html
今日推荐