【发布时间】:2021-03-08 00:23:03
【问题描述】:
您好,我最近创建了一个这样的表单:
<form method="post" Action="Save.php" enctype="multipart/form-data">
<label>Nome:</label><br><br>
<input name="Nome" ><br><br>
<label>Imagem:</label><br><br>
<div class='input-wrapper'>
<label for='input-file'>
Select a file
</label>
<input type="File" name="img" id="input-file"><br></div><br><label>Mensagem:</label><br><br><textarea name="msg"></textarea>
<br><br>
<input type="submit" class="btn_post">
</form>
而不是 save.php 看起来像这样:
<?php
// Here is more debug information:
$values = json_encode($_POST);
// Stores received values at the end of the file.
file_put_contents('save.json', $values, FILE_APPEND);
然后当我发送表单时,它在 save.json 中看起来像这样:
{"Nome":"Nicolas","img":"aef9bd64-6990-4f08-8238-2baf005f42f7.jpg","msg":"Incredible"}
到目前为止一切顺利,因为我得到了用户在输入文件中发送的文件的名称, 但我没有收到文件(图片),所以我把这段代码放在 ** Save.php ** 中,如下所示:
<?php
//
// Take the post request and transform it into JSON.
$values = json_encode($_POST);
// Stores received values at the end of the file.
file_put_contents('save.json', $values, FILE_APPEND);
$uploaddir = 'img/';
$uploadfile = $uploaddir . basename($_FILES['img']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['img']['tmp_name'], $uploadfile)) {
echo "Valid file and sent successfully.\ N";
} else {
echo "Possible file upload attack! \ N";
}
echo 'Here is more debug information:';
print_r($_FILES);
print "</pre>";
所以现在我在 $ uploaddir 中声明的文件夹中获取文件,加上 save.json 看起来像这样:
{"Nome":"Nicolas","msg":"Incredible"}
也就是说,我不再接收输入文件的值出了什么问题?
【问题讨论】:
-
您不会在 POST 数组中找到文件上传的详细信息 - 它们将在
$_FILES数组中 -
在存储 json 之前,您需要
$values中的路径 -
FILE_APPEND不会神奇地将逗号放在 json 对象字符串之间(也不会将整个文件包裹在方括号中)。换句话说,一旦你第二次将数据附加到文件中,你就有了无效的 json。