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

问题描述 投票:1回答:1

我需要将上传到表单的文件显示在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;
}

javascript php fetch
1个回答
0
投票

用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">

© www.soinside.com 2019 - 2024. All rights reserved.