ajax使用bootstrap验证器上传文件

时间:2017-09-13 07:17:48

标签: javascript jquery ajax validation

我第一次使用了bootstrap验证,一切正常,直到我尝试使用ajax上传照片,无论如何都无法正常工作。我希望我能在这里找到帮助

html表单

<div id="uploadAvatar" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="uploadAvatarForm" method="post" action="ajax/upload_avatar.php" enctype="multipart/form-data">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">تغيير الصورة</h4>
                </div>
                <div class="modal-body">
                    <span class="message-upload-error"></span>
                    <div class="form-group">
                        <label for="avatar" class="control-label"> حجم الصورة يجب أن لا يزيد على 10 ميغا </label>
                        <input type="file" name="avatar" id="avatar" />
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger pull-right btn-outline" data-dismiss="modal">الغاء</button>
                    <button type="submit" class="btn btn-success pull-right btn-outline" style="margin-left:4px;">رفع الملف</button>
                </div>
            </form>
        </div>
    </div>
</div>

验证

$('#uploadAvatarForm').bootstrapValidator({
        message: 'القيمة المدخلة غير صحيحة!',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            avatar: {
                validators: {
                    file: {
                        extension: 'jpeg,png,gif,jpg',
                        type: 'image/jpeg,image/png,image/gif,image/jpg',
                        maxSize: 2048 * 1024,
                        message: 'الرجاء آختيار صورة'
                    }
                }
            }
        }
    }).on('success.form.bv', function(e) {
        e.preventDefault();

        var $form    = $(e.target),
            formData = new FormData(),
            params   = $form.serializeArray(),
            files    = $form.find('[name="avatar"]')[0].files;
            formData.append('avatar',files);

            $.ajax({
                url: $form.attr('action'),
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(result) {
                    if(result !== 'Success'){
                        $('.message-upload-error').html(result);
                    }else{
                        $('#uploadAvatar').modal('hide');
                    }
                }
            });

    });

我已经尝试了很多东西让它起作用但没有意义:\就像我在浪费时间一无所有

0 个答案:

没有答案