繁体   English   中英

数组 $data ['image'] 显示为空数组,无法将文件发送到 php

[英]the array $data ['image'] is displayed as an empty array, it is not possible to send a file to php

我需要上传到表格的文件显示在 php 数组中,但我是空的,为什么? 如果有人回复我将不胜感激

这是我需要的结果:

Array
(
  [image] => Array 
      (
        [name] => name
        [type] => type
        [tmp_name] => C:\...
        [error] => 0
        [size] => 66666
      )
)
 <form action="" id="form">
        <p>Title: <input type="text" method="post" name="title" id="title" enctype= "multipart/form-data"></p>
        <p>Min description:  <textarea name="descr-min" id="descr-min"></textarea></p>
        <p>Description: <textarea name="description" id="description"></textarea></p>
        <p>Photo: <input type="file" name="image" id="image"></p>
        <input type="submit" value="add">
    </form>
    <script src="/js/scripts.js"></script>




document.querySelector('#form').onsubmit = function(event) {

  let formData = new FormData(this);
  formData.append('action', 'addfile');

  event.preventDefault();
  fetch('data.php', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data'
      },
      body: JSON.stringify(Object.fromEntries(formData)), 

  }).then((response) => response.text())
    .then((text) => {
      console.log(text);
    })
}




<?php
require_once 'add.php';

// $action = $_POST['gg'];
$json = file_get_contents('php://input');
$data = json_decode($json);
$data = json_decode(json_encode($data), true);
print_r($data); 
// this prints out:  
// Array
// (
//     [title] => asd
//     [descr-min] => ds
//     [description] => a
//     [image] => Array
//         (
//         )

//     [action] => addfile
// )
switch ($data['action']) {
    case 'addfile';
    addNews($data);
    break;
}

PHP 中的文件上传存储在$_FILES超全局变量中。 您可以使用文件输入的name属性作为数组键访问文件上传,例如$_FILES['image']

您可以使用$_FILES['image']['tmp_name']访问此文件的临时路径

有关详细信息,请参阅https://www.php.net/manual/en/features.file-upload.php

编辑:确保您的表单具有属性 enctype="multipart/form-data" 以允许将文件正确上传到服务器。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM