JQuery ajax FormData:文件未添加到POST

时间:2017-12-26 17:15:06

标签: jquery ajax post file-upload

尝试从上面的代码中上传文件var_dump($_POST),表明ajax没有设置$_POST['file']。除此之外我没有任何错误消息,所以我不知道哪里出错了。

VAR DUMP RESULT

array(1) {
["action"]=>
string(20) "uploadNewUserPicture"
}

HTML

<div id="userInfoUploadProfilePic">   
  <form id="userUploadProfilePicForm" method="post" enctype="multipart/form-data">
  <div class="userInfoFormTitle">UPLOAD PROFILE PICTURE</div>
  <input type="file" name="fileToUpload" id="userImg"></input>
  <br>
  <input id="submitPictureButton" type="button" value="Upload Image" name="submit">
  </form>
</div

JS

var file = $('#userImg')[0].files[0];
var formData = new FormData();

formData.append('action', 'uploadNewUserPicture');
formData.append('file', file );

$.ajax({
     url: "php/upload.php",
     type: "post",
     processData: false,
     contentType: false,
     data: formData,
     success: function(result) {
      console.log(result);
     },
    error: handleAjaxError,
   });

PHP

if(isset($_POST['action']) && !empty($_POST['action'])) {
  var_dump($_POST);
  $action = $_POST['action'];
  $var = $_POST['file'];

  switch($action) {
   case 'uploadNewUserPicture' : uploadNewUserPicture($var);break;
  }
};

1 个答案:

答案 0 :(得分:0)

上传文件时,您需要使用$_FILES

  

$ _ FILES通过HTTP POST方法上传到当前脚本的关联项目数组。 POST方法上传部分概述了此数组的结构。

$fileName = $_FILES['fileToUpload']['name']; 
$fileTmpName = $_FILES['fileToUpload']['tmp_name']; 

要上传文件,在PHP中需要文件的tmp_namename。您的uploadNewUserPicture($var)函数应具有以下参数签名

uploadNewUserPicture($tmp_name, $image_name);