Javascript 数组$data[';image';]显示为空数组,无法将文件发送到php
我需要上传到表单的文件在php数组中显示,但我的文件是空的,为什么?如果有人回复,我将不胜感激 以下是我需要的结果:Javascript 数组$data[';image';]显示为空数组,无法将文件发送到php,javascript,php,fetch,Javascript,Php,Fetch,我需要上传到表单的文件在php数组中显示,但我的文件是空的,为什么?如果有人回复,我将不胜感激 以下是我需要的结果: Array ( [image] => Array ( [name] => name [type] => type [tmp_name] => C:\... [error] => 0 [size] => 66666 ) ) 标题: 最
Array
(
[image] => Array
(
[name] => name
[type] => type
[tmp_name] => C:\...
[error] => 0
[size] => 66666
)
)
标题:
最小说明:
说明:
照片:
document.querySelector(“#form”).onsubmit=函数(事件){
设formData=新formData(本);
append('action','addfile');
event.preventDefault();
fetch('data.php'{
方法:“POST”,
标题:{
“接受”:“应用程序/json”,
“内容类型”:“多部分/表单数据”
},
正文:JSON.stringify(Object.fromEntries(formData)),
}).然后((response)=>response.text())
。然后((文本)=>{
console.log(文本);
})
}
PHP中的文件上载存储在$\u FILES
超全局变量中。您可以使用文件输入的name
属性作为数组键访问文件上载,例如$\u FILES['image']
您可以使用$\u FILES['image']['tmp\u name']
有关更多信息,请参阅
编辑:确保表单具有属性enctype=“multipart/form data”,以允许将文件正确上载到服务器
PHP中的文件上载存储在$\u FILES
超全局变量中。您可以使用文件输入的name
属性作为数组键访问文件上载,例如$\u FILES['image']
您可以使用$\u FILES['image']['tmp\u name']
有关更多信息,请参阅
编辑:确保表单具有属性enctype=“multipart/form data”,以允许将文件正确上载到服务器
问题在于,我不是通过表单直接传递文件,而是通过请求传递文件,也就是说,文件不应该传递给全局变量$\u file,而是传递给$data。表格是写的correctly@Ilkara然后我建议在上传时对文件进行base64编码,然后在用户收到文件时解码并保存server@Ilkara抱歉,我误解了您的问题BTW问题是我没有通过表单直接传递文件,而是通过请求传递,也就是说,文件不应该传递到全局变量$\u file,但是,我们需要更多的数据。表格是写的correctly@Ilkara然后我建议在上传时对文件进行base64编码,然后在用户收到文件时解码并保存server@Ilkara对不起,我误解了你的问题
<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;
}