dourao1896 2019-02-05 03:18
浏览 117

使用PHP从FormData检索文件

I am attempting to send an image from the client to a PHP file that will upload the image into a preset directory. I am not sure why I cannot seem to get the following code to accomplish this task.

JS File:

function update_avatar(){

var file = document.getElementById('avatar');
var formData = new FormData(file);
//formData.append("avatar",file);

if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {  // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {

  var r = JSON.parse(this.responseText);
  console.log(r);
  if(r.status === 'GOOD'){
    document.getElementById('pForm_response').innerHTML = 'Your Avatar Was Updated Successfully!';
    setTimeout(function(){
      document.getElementById('pForm_response').innerHTML = '';
    },5000);
    //Change Avatar Image URL...
    document.getElementById('avatarPreview').href = r.newURL;
    window.scrollTo(0, 0);
  }else{
    document.getElementById('pForm_error').innerHTML = 'There was an error processing your request...';
    setTimeout(function(){
      document.getElementById('pForm_error').innerHTML = '';
    },5000);
    window.scrollTo(0, 0);
  }

}
 }
  xmlhttp.open("POST","user-settings/php/update-avatar.php",true);
  xmlhttp.setRequestHeader('Content-Type','multipart/form-data');
  //xmlhttp.setRequestHeader('Content-type', 'application/x-www-form- 
urlencoded');
  xmlhttp.send(formData);
}

PHP File:

    <?php
 include '../../assets/php/connection.php';

$eMessages = '';

print_r($_POST);
print_r($_FILES);

//echo $_FILES['avatar']['size'];//For DeBug ONLY...
if($_FILES['avatar']['size'] != 0) {
$id = rand(100000,1000000);

//Document Parsing
$target_dir = "../../assets/img/avatars/";
$target_file2 = $target_dir . basename($_FILES["avatar"]["name"]);

$uploadOk = 1;
$imageFileType = pathinfo($target_file2,PATHINFO_EXTENSION);
$target_file = $target_dir . $_SESSION['user_id'] . "_avatarImg_" . 
$id . "." . $imageFileType;

// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["avatar"]["tmp_name"]);
if($check !== false) {
  //  echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    $eMessages .= "File is not an image.";
    $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && 
$imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "JPG" && 
$imageFileType != "PNG" ) {
$eMessages .= "<br>ERROR!- only JPG, JPEG, PDF, PNG & GIF files are 
allowed.";
$uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$eMessages .= "<br>ERROR!- your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["avatar"]["tmp_name"], $target_file)) {
  //INSERT FILE PATH INTO DATABASE
  $file_name_1 = 'http://' . $_SERVER['HTTP_HOST'] . 
'/toolbox/assets/img/avatars/' . $_SESSION['user_id'] . '_docImg_' . 
$id . '.' . $imageFileType;
  //echo '<br>File was moved to the right location!';
}
}
}else{
//Set URL to empty if no file was selected to upload...
$file_name_1 = '';
$uploadOk = 0;
$eMessages .= 'Size of Image not detected!';
}//End if file was uploaded

//echo $eMessages;
$q = "UPDATE `users` SET `avatar_url` = '" . $file_name_1 . "' WHERE 
`ID` = '" . $_SESSION['user_id'] . "'";
if($uploadOK != 0){
mysqli_query($ign_conn, $q) or die($ign_conn->error);
$x->status = 'GOOD';
$x->response = 'Avatar Updated Successfully...';
$x->newURL = $file_name_1;
}else{
$x->status = 'BAD';
$x->response = $eMessages;
}
$response = json_encode($x);
echo $response;

?>

I am using $_FILES['avatar']['size'] to try and detect the image and I get nothing...

EDIT: When I use this code in the PHP file:

print_r($_POST);
print_r($_FILES);

The output is:

Array
(
)
Array
(
)

I am still not sure why my values are empty?

Additionally, this is my Request Payload:

------WebKitFormBoundaryzBMoLRhnxawwcEQR--
  • 写回答

1条回答 默认 最新

  • dop20345 2019-02-05 15:45
    关注

    After further research, I did find an answer that solved my problem here: javascript xhr file upload without jQuery

    It appears that the correct use of FormData() for files has 3 parameters. Not 2.

    Also, it was suggested not to set the setRequestHeader() as xhr will automatically do this.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!