我正在尝试通过php&ajax将image从html页面以modal的形式从html页面上传到数据库,但是它不起作用,我不知道为什么,有人可以帮助我吗?

HTML页面

<form method="post" enctype="multipart/form-data">
    <div class="row">
      <div class="col-sm-4">
        <label class="Modallabel">Photo:</label>
      </div>
      <div class="col-sm-8">
        <div class="input-group input-group-sm" style="margin-top: -5px;">
            <input type="file" id="fileUpload" name="fileUpload" style="color: #ffffff;"/>
        </div><br>
      </div>
    </div>
</form>
<button type="button" class="btn btn-success btn-md" style="margin:0;width: 75px;" onclick="AddNewCustomer()">Add</button>


Javascript功能

function AddNewCustomer()
{
//Image upload
$(document).ready(function()
{
    $(document).on('change', '#fileUpload', function() //NOT WORKING HERE
    {
        var property = document.getElementById("fileUpload").files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();
        if (jQuery.inArray(image_extension, ['gif','png','jpg','jpeg']) == -1)
        {
            alert("invalid Image File");
        }
        var image_size = property.size;
        if(image_size > 2000000)
        {
            alert("Image File Size is very big");
        }
        else
        {
            var form_data = new FormData();
            form_data.append("fileUpload", property);

            $.ajax
            ({
                type:"POST",
                url:"addNewCustomer.php",
                processData: false,
                cache: false,
                contentType: false,
                data:
                    {
                    'form_data':form_data
                    },
                success: function(data){
                    if (data == "Success!")
                    {
                        sweetAlert("Data entered successfully!");
                    }
                    else if(data == "Exist")
                    {
                        sweetAlert("","Customer already exists!","error");
                        return false;
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log('ERROR', textStatus, errorThrown);
                }
            })
        }
    })
})

}

最佳答案

单击change处的<button>后,将附加onclick="AddNewCustomer()事件。

您可以删除AddNewCustomer函数,并在单击change元素时在#fileUpload元素上调用.btn

$(document).ready(function() {
  $(document).on('change', '#fileUpload', function() {//do stuff})

  $(".btn").on("click", function() {
    $("#fileUpload").trigger("change");
  });
});

关于javascript - 在php和ajax中将图像上传到数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44144952/

10-12 15:50