【问题标题】:Undefined index for input type of file [duplicate]文件输入类型的未定义索引[重复]
【发布时间】:2018-09-24 15:07:06
【问题描述】:

我有一个名为 file 的输入文件,但在提交表单后,它会返回:

未定义索引:第 26 行 C:\xampp\htdocs\Rehab\image_upload\index.php 中的文件。

第 26 行指的是:$file = $_FILES['file'];

这是我的html:

<form class="container-fluid d-flex justify-content-between" action="index.php" method="POST">
  <div class="col-md-4 mt-5 border-right pr-5 mr-5">
    <div class="form-group text-center">
      <legend class="display-4">Image Upload</legend>
    </div>
    <div class="form-group">
      <label for="title">Title</label>
      <input type="text" class="form-control" name="title" id="title" autocomplete="off">
    </div>
    <div class="form-group">
      <label for="image">Image</label>
      <input type="file" class="form-control" name="file" id="name">
    </div>
    <div class="form-group text-center">
      <button class="btn btn-outline-primary" name="submit">Post</button>
    </div>
  </div>
  <div class="col-md"></div>
</form>

这是我的 php 代码:

if(isset($_POST['submit'])){
  $file = $_FILES['file'];

  if ($file['error'] > 0) {
    return echo "Error!";
  }

  if($error === 0){
    $name = $file['name'];
    $type = $file['type'];
    $size = $file['size'];
    $tmp_name = $file['tmp_name'];

    $name_explode = explode('.', $name);
    $file_ext = strtolower($name_explode[1]);

    $allowed = array('jpg','jpeg','png','gif');

    if(!in_array($file_ext, $allowed)) {
      return echo "Invalid file type!";
    }

    $new_name = uniqid('', true) . "." . $file_ext;
    $location = 'assets/images/' . $new_name;
    $query = $conn->query("INSERT INTO medicine VALUES ()");
    $move = move_uploaded_file($tmp_name, $location);
  }
}

【问题讨论】:

  • 我刚刚从我以前的项目中复制了代码,效果很好
  • 没关系,解决了!哈哈哈
  • 是您表单中缺少的enctype="multipart/form-data" 吗?如果您将您的“解决方案”发布给可能有类似问题的其他人,那就太好了
  • 是的,enctype="multipart/form-data"
  • 对不起,我忘了发布答案:(

标签: php mysql file-upload


【解决方案1】:

您需要在表单标签中添加enctype="multipart/form-data"。因为enctype 属性用于&lt;input type="file"&gt; 你的标签应该是

<form class="container-fluid d-flex justify-content-between" action="index.php" method="POST" enctype="multipart/form-data">

【讨论】:

    猜你喜欢
    • 2021-10-24
    • 2017-11-12
    • 1970-01-01
    • 2020-11-01
    • 2016-06-10
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2020-12-11
    相关资源
    最近更新 更多