为什么$ _FILES []总是为空? [英] Why is $_FILES[] always empty?

查看:53
本文介绍了为什么$ _FILES []总是为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Php和Javascript制作AJAX文件上传器.我遇到的问题是在我尝试使用 move_uploaded_file 函数, $ _ FILES 数组的 upload.php 脚本中始终为空.

I'm trying to make an AJAX file uploader with Php and Javascript. The problem I'm having is that in my upload.php script where I'm trying to use the move_uploaded_file function, the $_FILES array is always empty.

  • /etc/php/7.2/apache2/php.ini
  • 中选中的 file_uploads = On
  • 检查了 uploader.php upload.php
  • 的当前工作目录
  • 检查了上传
  • 的文件权限
  • 更改了/etc/php/7.2/apache2/php.ini
  • 中的 uploads_tmp_dir

uploader.php中的HTML:

<form class="form" id="upload_form">
    <input type="file" name="file_to_upload" id="file_to_upload"><br>
    <input class="button" type="submit" value="Upload">
</form>

uploader.php中的Javascript:

<script>
  var upload_form    = document.getElementById('upload_form');
  var file_to_upload = document.getElementById('file_to_upload');

  upload_form.addEventListener("submit", upload_file);

  function upload_file (e) {
    e.preventDefault();

    var xhr = new XMLHttpRequest()
    xhr.open("POST", "upload.php");
    xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.send(new FormData(upload_form));
  }
</script>

upload.php:

<?php
//$target_path = "uploads/".basename($_FILES["file_to_upload"]["name"]);
$uploaded_file = $_FILES['file_to_upload']['tmp_name'];
var_dump($_FILES); // This is always array(0) { }

if(file_exists($uploadedFile)) {
   echo "file uploaded to temp dir";
} else {
   echo "file upload failed"; // This is always the outcome
}
//move_uploaded_file($_FILES["file_to_upload"]["tmp_name"], $target_path);
?>

推荐答案

根据.您还必须指定 method ="post" -请参阅以下答案一个解释.

According to the PHP docs, you must specify enctype="multipart/form-data". You must also specify method="post" -- see this answer for an explanation.

因此,您的< form> 应该显示为:

So your <form> should read:

<form class="form" id="upload_form" enctype="multipart/form-data" method="post">

这篇关于为什么$ _FILES []总是为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆