PHP Ajax文件上传无法正常工作

时间:2017-07-07 13:57:44

标签: php jquery ajax

请帮我在这里找到问题。我试图通过AJAX上传文件但由于某些原因,我不知道这个代码已经拒绝工作,即上传的文件没有复制到该位置。

function save()
{
    var fileUpload = $("#files").get(0);
    var files = fileUpload.files;
    var data = new FormData();
    for (var i = 0; i < files.length ; i++) {
       data.append('files',files[i],files[i].name);
    }

    var datastring = $("#businessform").serializeArray();
    $.each(datastring,function(key,input){
        data.append(input.name,input.value);
    });

    $.ajax({
            type: "POST",
            url: "../include/update_ajax.php",
            contentType: false,
            processData: false,
            data: data,
            dataType: 'json',
            cache: false,
            success: function(data) {
                //do something
            },
            error: function(){
                  alert('error handling here');
            }
        });
 }

这是PHP

        $success = 0;
        $logo = "";
        $logo_error = 0;
        $sql = "update business set businessname=:bname, phone=:phone, email=:email where vendorid = :id";
        $fields = array(
            ':bname'=>$_POST['businessname'],
            ':phone'=>$_POST['businessphone'],
            ':email'=>$_POST['businessemail'],               
            ':id'=>$_POST['vendorid']
        );
        $q=$con->update_query($sql,$fields);
        if($q)
        {
            //save logo
            $businessid = $con->lastID;
            if(!empty($_FILES['files']['tmp_name']))
            {
                $ext=pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
                if(strcasecmp($ext, "jpeg") == 0 || strcasecmp($ext, "jpg") == 0 || strcasecmp($ext, "png") == 0)
                {
                    $logo = "logo".$businessid;
                    move_uploaded_file($_FILES['files']['tmp_name'], UPLOADS_FOLDER.$logo);
                }
                else
                {
                    $logo_error = 1;
                }

            }
            $success = 1;
        }
        echo json_encode(array('success'=>$success, 'logo_error'=>$logo_error));

附加的序列化表单发送和插入没有问题,但上传的文件不是以这种方式发送的。请问我做错了什么,以及更好的方式。

非常感谢你。

1 个答案:

答案 0 :(得分:0)

您不需要在FormData()中附加文件,只需将表格标签选择器放在FormData($("#businessform")[0])侧;

function save()
{
    var datastring = FormData($("#businessform")[0]);

    $.ajax({
            type: "POST",
            url: "../include/update_ajax.php",
            contentType: false,
            processData: false,
            data: data,
            dataType: 'json',
            cache: false,
            success: function(data) {
                //do something
            },
            error: function(){
                  alert('error handling here');
            }
        });
 }