尝试从上面的代码中上传文件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;
}
};
答案 0 :(得分:0)
上传文件时,您需要使用$_FILES
$ _ FILES通过HTTP POST方法上传到当前脚本的关联项目数组。 POST方法上传部分概述了此数组的结构。
$fileName = $_FILES['fileToUpload']['name'];
$fileTmpName = $_FILES['fileToUpload']['tmp_name'];
要上传文件,在PHP中需要文件的tmp_name
和name
。您的uploadNewUserPicture($var)
函数应具有以下参数签名
uploadNewUserPicture($tmp_name, $image_name);