选择文件后如何自动提交上传表单?如何替换上传按钮我的代码如下

时间:2018-03-19 08:52:36

标签: javascript php ajax

代码:

<script type='text/javascript'>
            $(document).ready(function(){

                // Upload
                $("#but_upload").click(function(){

                    var fd = new FormData();
                    var files = $('#file')[0].files[0];
                    fd.append('file',files);
                    fd.append('request',1);

                    // AJAX request
                    $.ajax({
                        url: 'addremove.php',
                        type: 'post',
                        data: fd,
                        contentType: false,
                        processData: false,
                        success: function(response){

                            if(response != 0){
                                var count = $('.uploaded-images .image-content').length;
                                count = Number(count) + 1;

                                // Show image preview with Delete button
                                $('.uploaded-images').append("<div class='image-content' id='content_"+count+"' ><img class='image-responsive' src='"+response+"' width='125' height='125'><span class='delete' id='delete_"+count+"'>&times;</span><span class='under-approval'>Under Approval</span></div>");
                            }else{
                                alert('file not uploaded');
                            }
                        }
                    });
                });

                // Remove file
                $('.uploaded-images').on('click','.image-content .delete',function(){

                    var id = this.id;
                    var split_id = id.split('_');
                    var num = split_id[1];

                     // Get image source
                    var imgElement_src = $( '#content_'+num+' img' ).attr("src");

                    // AJAX request
                    $.ajax({
                       url: 'addremove.php',
                       type: 'post',
                       data: {path: imgElement_src,request: 2},
                       success: function(response){

                            // Remove <div >
                            if(response == 1){
                                $('#content_'+num).remove();
                            }

                       }
                    });
                });

            });
        </script>

这是我的问题:

  1. 如何在选择文件时自动提交上传表单?
  2. 如何替换上传按钮我的代码在下面
  3. 任何有此领域经验的人,请建议我解决这个问题,谢谢。

2 个答案:

答案 0 :(得分:-1)

您可以使用以下vertx.io代码:

Powermock

答案 1 :(得分:-1)

您可以使用:

$('#file').on('change', function() {
    $("#but_upload").click();
});

或者更好的只是将您的点击代码放入更改事件。

$('#file').on('change', function() {
   var fd = new FormData();
   var files = this.files[0];
   ...
});
相关问题