当表单通过jquery将数据发送到另一个php文件时,文件上载不起作用

时间:2016-11-30 12:31:22

标签: php file-upload

当我在同一页面中执行PHP时,下面的代码效果很好但是当我使用jquery执行script_add_business.php时它不起作用。特别是HTML html文件上传不会发送任何值,但是当我尝试获取其他字段值如textbox时,我成功地获取了它们。

我的HTML:

<form method="post" enctype="multipart/form-data" id="addBusinessForm" class="form-horizontal addBusinessForm" action="">
<input type="file" name="logo" class="form-control">
<button type="submit" id="addBusiness" class="btn btn-custom">Upload Logo</button>
</form>

HTML页面中的JQUERY:

<script type="text/javascript">
    //Add Invoice Form
    $('#addBusiness').click(function() {
      $.post("script_add_business.php", $(".addBusinessForm").serialize(), function(response) {
        $('#success').html(response);
        $('#success').show();
        if (response == 'OK') {
            $('#addBusinessForm')[0].reset();
            $('#success').text('Your Business has been successfully submitted. People can see it live once we approve it.');
        }
      });
      return false;
    });
    </script>

script_add_business.php代码:

if(!empty($_FILES['logo']['name']))
        {
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["logo"]["name"]);
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            $imgname = basename($_FILES["logo"]["name"]);
            $target_file = $target_dir .$imgname;
            echo "File path is:". $target_file; exit;
}

我真的很感激帮助。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

您无法使用jQuery $ .post方法上传文件。

试试这样。

<form method="post" enctype="multipart/form-data" id="addBusinessForm" class="form-horizontal addBusinessForm" action="">
        <input type="file" name="logo" class="form-control">
        <button type="submit" id="addBusiness" class="btn btn-custom">Upload Logo</button>
    </form>


$('#addBusiness').click(function() {

            var formData=new FormData();

            formData.append("image",$('[name="logo"]')[0].files[0]);

            $.ajax({
                url: 'script_add_business.php',
                data:formData,
                type: 'POST',
                dataType:"JSON",
                cache: false,
                contentType: false,
                processData: false,
                success:function(response){ 
                    // Do stuffffff
                }
            });
            return false;
        });