以下代码从表单中读取数据并将文件保存在文件夹中并将其写入JSON文件:
使用Javascript:
var name = $("#name").val();
var image = $("#image")[0].files[0];
var model = $("#model")[0].files[0];
var type = $("#type").val();
var formData = new FormData();
formData.append('name',name);
formData.append('image',image);
formData.append('model',model);
formData.append('type',type);
$.ajax({
url: 'php/form-process.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',
dataType: 'json',
success: function(data){
// get server responce here
alert(data);
// clear file field
$("#image").val("");
}
});
PHP :
$filename = "itemsData";
$itemsFile = '../json/'.$filename.".json";
if( !empty( $_POST ) ){
$data = json_encode( $_POST );
if( json_last_error() != JSON_ERROR_NONE ){
exit;
}
if (!isset($_FILES['image']) || !is_uploaded_file($_FILES['image']['tmp_name'])) {
echo 'No file send...';
exit;
}
$uploaddir = '../upload/';
$userfile_tmp = $_FILES['image']['tmp_name'];
$userfile_name = $_FILES['image']['name'];
if (move_uploaded_file($userfile_tmp, $uploaddir . $userfile_name)) {
echo 'File send.';
}else{
echo 'Upload Invalid!';
}
//Get data from existing json file
$file = file_get_contents($itemsFile);
// converts json data into array
$data = json_decode($file,true);
$data[] = array(
'name' => $_POST['name'],
'image' => $_POST['image'],
'model' => $_POST['model'],
'type' => $_POST['type']
);
//Convert updated array to JSON
$file = json_encode($data, JSON_PRETTY_PRINT);
//write json data into data.json file
file_put_contents($itemsFile,$file);
}
JSONfile返回:
[
{
"name": "chair",
"image": null,
"model": null,
"type": "1"
}
]
图片是jpg,png等;
model是一个.js文件 我如何在JSON文件中输入文件路径?
[
{
"name": "chair",
"image": /image/nameOfFile.jpg,
"model": /code/nameOfFile.js,
"type": "1"
}
]
答案 0 :(得分:0)
如果我理解正确,您应该直接在JSON中创建文件路径
$data[] = [
'name' => $_POST['name'],
'image' => $uploaddir . $userfile_name,
'model' => $_POST['model'],
'type' => $_POST['type']
];
从PHP 5.4开始,您还可以使用短数组语法,将array()替换为[]。
另一个选项是将上传的图像编码为base64,并将整个图像保存为JSON
编辑,因为这段代码容易受到攻击,你应该做这样的事情
$name = stripslashes($_POST['name']);
$model = stripslashes($_POST['model']);
$type = stripslashes($_POST['type']);
$data[] = [
'name' => $name,
'image' => $uploaddir . $userfile_name,
'model' => $model,
'type' => $type
];