使用AJAX和PHP上传图像和其他信息 - 无法识别文件名

时间:2017-06-24 07:12:57

标签: php ajax file post

我在XAMPP服务器上使用PHP和AJAX调用。

我已经有了这个,您可以上传照片和其他信息,例如名称。代码很长,所以我稍微编辑它并放一个简短的版本,以帮助你看到我的内容。

形式:

<form class="form-horizontal" role="form" action="" method="POST" enctype="multipart/form-data">
        <fieldset>
          <legend>My photo</legend>
            <img src="img/avatar-placeholder.jpg" class="center-block"/>
        </fieldset>


        <div class="form-group">
          <div class="col-md-12 text-center">
            <input name="pic" type="file" id="pic">
          </div>
        </div>

      <fieldset>
        <legend>My info</legend>
        <div class="col-md-6">
          <div class="form-group">
            <label class="col-sm-2 control-label" for="textinput">Name: </label>
            <div class="col-sm-10">
              <input type="text" placeholder="" class="form-control" id="name" name="name">
            </div>
          </div>
        </div>
      </fieldset>

      <button type="button" id="boton" class="btn boton2 textoBoldBlanco" onclick="addInfo()">Add Info <i class="fa fa-plus" aria-hidden="true" id="icono"></i></button>
</form>

此表单的按钮与JS事件有关,在该事件中我获取数据并进行AJAX调用:

function addInfo(){

    picture = document.getElementById("pic").files[0].name;
    name = document.getElementById("name").value;

        $.ajax({

                url: "http://localhost/myProject/extras/processInfo.php", 
                type: "POST",
                data: {"picture": picture,
                       "name": name, 
                       },
                dataType: "html",
                cache: false,
                beforeSend: function() {    
                    console.log("Processing...");
                },
                success: 
                    function(data){
                        if(data == "SUCCESS"){
                            alert("Info added");
                        }else{
                            alert("Can't add info");
                        }
                    }

    });

}else{
    alert("Incorrect");
}

}

现在,这是PHP文件:

 if(isset($_POST['picture'])){

        $uploadDir = '../img/pictures/';

        $fileName = $_FILES['pic']['name'];
        $fileType = $_FILES['pic']['type'];
        $tmpName = $_FILES['pic']['tmp_name'];

        $filePath = $uploadDir . $fileName;
        $result = move_uploaded_file($tmpName, $filePath); 

}

if((isset($_POST['name'])) && (!empty($_POST['name']))){
    $name = $_POST['name'];
}else{
    $errores .= "<p class='alerta'>Error</p>";
}

//Query part
$stmt = $con->prepare("INSERT INTO info (picture, name) VALUES (?, ?)");

$stmt->bind_param('ss', $filePath, $name);

$stmt->execute();

$affectedRows = $stmt->affected_rows;

if($affectedRows > 0){
    echo "SUCCESS";
}else{
    echo "FAILED";
}

这或多或少是PHP代码,注意:它已经与数据库工作连接。

问题是......在选择照片并添加名称后,我使用JS正确获取所有值(我已经尝试过console.log()来检查)然后AJAX调用触发..然后,即使信息被添加到数据库中,它仍然会说&#34; CAN&#39;添加信息&#34; ...

但是,还有第二个问题:尽管消息失败,添加到数据库的路径不正确,看起来像这样(如变量$ uploadDir only - &gt;&#39; ../ img / pictures /&#39;)这就是存储为路径的所有内容......似乎它不能识别文件的名称。

我怀疑$ _FILES []部分,因为POST收到一个简单的字符串,类似&#34; myface.jpg&#34;仅 - &gt;在JS文件中,我已经完成了这个&#34; picture = document.getElementById(&#34; pic&#34;)。files [0] .name;&#34;因为如果没有,它会说&#34; C:// fakepath&#34;和文件的名称(我在Chrome浏览器上)

任何想法,帮助,将不胜感激:)提前感谢!

1 个答案:

答案 0 :(得分:1)

表单的名称已分配给Javascript / jQuery函数使用,但与问题中发布的名称相同。

<form name='uploads' class="form-horizontal" role="form" action="" method="POST" enctype="multipart/form-data">
        <fieldset>
          <legend>My photo</legend>
            <img src="/images/Grumpy_OK.jpg" class="center-block"/>
        </fieldset>


        <div class="form-group">
          <div class="col-md-12 text-center">
            <input name="pic" type="file" id="pic">
          </div>
        </div>

      <fieldset>
        <legend>My info</legend>
        <div class="col-md-6">
          <div class="form-group">
            <label class="col-sm-2 control-label" for="textinput">Name: </label>
            <div class="col-sm-10">
              <input type="text" placeholder="" class="form-control" id="name" name="name">
            </div>
          </div>
        </div>
      </fieldset>

      <button type="button" id="boton" class="btn boton2 textoBoldBlanco" onclick="addInfo()">Add Info <i class="fa fa-plus" aria-hidden="true" id="icono"></i></button>
</form>

jQuery函数使用FormData Object将内容(包括文件)发送到PHP上传处理程序。发送的POSTed数据将包含所有必需的数据,但您始终可以将其他项添加到POST阵列,如下所示,我添加了参数fieldname

function addInfo(){
    var form=document.forms['uploads'];
    var data=new FormData( form );
        data.append('fieldname','pic');


    $.ajax({
        url: '/test/uploadhandler.php',/* Change this to your upload handler script */
        data: data,
        type: 'POST',
        contentType: false,
        processData: false,
        cache: false,
        beforeSend: function() {    
            console.log("Processing...");
        },
        success: function(r){
            alert( r == 'SUCCESS' ? 'Info added' : 'Can\'t add info' );
        }
    });
}

用于处理上传的PHP脚本〜由于文件系统结构和数据库而未经过全面测试,但实际上传是使用不同的目标目录测试的。

if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['name'], $_POST['fieldname'] ) ){

    $name=$_POST['name'];
    $action=$_POST['action'];
    $fieldname=$_POST['fieldname'];

    $uploadDir = '../img/pictures/';

    function uploaderror( $code ){ 
        switch( $code ) { 
            case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
            case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
            case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
            case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
            case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
            case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
            case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
            default: return "Unknown upload error";
        }
    }

    if( $action=='fileupload' ){
        $obj=(object)$_FILES[ $fieldname ];

        $name=$obj->name;
        $tmp=$obj->tmp_name;
        $size=$obj->size;
        $type=$obj->type;
        $error=$obj->error;

        if( $error == UPLOAD_ERR_OK ){

            $ext=pathinfo( $name, PATHINFO_EXTENSION );
            $targetpath = $uploadDir . $name;
            /* You might want to do some sanity checks on the submitted data and image */

            /* Move the file to it's new location */
            $status = move_uploaded_file( $tmp, $targetpath );



            if( $status ){

                $sql='insert into `info` (`picture`, `name`) values ( ?, ? )';
                $stmt = $con->prepare( $sql );

                if( $stmt ){

                    $stmt->bind_param('ss',$targetpath,$name);
                    $result=$stmt->execute();
                    $rows = $result ? $stmt->affected_rows : 0;

                    exit( $result & $rows ? 'SUCCESS' : 'FAILED' );
                }
            }


        } else {
            exit( uploaderror( $error ) );
        }
    }
}