我需要上传到表单中的文件在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;
}
发布于 2019-11-11 16:06:25
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">
https://stackoverflow.com/questions/58804690
复制