js實現上傳文件動態展示在前端並通過ajax上傳到后端


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="/static/bs-3.3.7/css/bootstrap.css">
    <script src="/static/bs-3.3.7/js/bootstrap.min.js"></script>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3"></div>
        <h1 class="text-center">注冊</h1>
        <hr>
        <form id="myform" novalidate>
            {% csrf_token %}
            {% for foo in form_obj %}
                <div class="form-group">
                    <label for="{{ foo.auto_id }}">{{ foo.label }}</label>
                    {{ foo }}
                    <span class="pull-right"></span>
                </div>
            {% endfor %}
            <div class="form-group">
                <label for="id_file">頭像
                    <img src="/static/image/default.jpg" alt="" width="80" style="margin-left: 20px" id="id_img">
                </label>
                <input type="file" name="myfile" id="id_file" class="hidden">
            </div>
            <input type="button" class="btn btn-success pull-right" value="注冊" id="id_submit">
        </form>
    </div>
</div>
<script>
    $("#id_file").change(function () {
        // 獲取文件對象
        var fileObj = $(this)[0].files[0];
        //利用內置對象文件閱讀器生成文件對象的二進制數據
        var fileReader = new FileReader();
        //將文件對象交給文件閱讀器,生成文件對象的二進制數據
        fileReader.readAsDataURL(fileObj); //異步
        fileReader.onload = function () {
            $("#id_img").attr('src', fileReader.result);
        }
    });

    // 點擊注冊按鈕 觸發點擊事件
    $('#id_submit').click(function () {
        // 利用內置對象FormData完成既有普通鍵值又有文件數據的發送
        var formData = new FormData();
        // 添加普通鍵值對
        // formData.append('','')
        // console.log($('#myform').serializeArray());  // 會將form標簽內 普通的鍵值對 自動組成一個數組的形式返回給你
        $.each($('#myform').serializeArray(), function (index, obj) {  // $.each(你想要被循環的對象,函數(索引,單個單個的對象))
            // console.log(index,obj)
            formData.append(obj.name, obj.value)  // 僅僅是將普通的鍵值對添加進去
        });
        // 添加文件數據
        formData.append('my_avatar', $('#id_file')[0].files[0]);
        // ajax發送
        $.ajax({
            url: '',
            type: 'post',
            data: formData,

            contentType: false,
            processData: false,

            success: function (data) {
                if (data.code == 2000) {
                    location.href = data.url
                } else {
                    // console.log(data.msg)
                    $.each(data.msg, function (index, obj) {
                        console.log(index,obj);
                        var targetId = '#id_' + index;
                        $(targetId).next().text(obj[0]).addClass('error').parent().addClass('has-error')
                    })
                }
            }
        })
    });
        $('input').focus(function () {
        // 將當前input所在的div移除has-error屬性 並將下面的span標簽內的內容也移除了
        $(this).next().text('').removeClass('error').parent().removeClass('has-error')
    })
</script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM