JQuery ajax FormData:文件未添加到POST

问题描述 投票:0回答:1

尝试上传文件,下面的代码中的var_dump($_POST)显示ajax没有设置$_POST['file']。我没有其他错误消息所以我不知道我哪里出错。

是否有结果

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;
  }
};
jquery ajax post file-upload
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.