gpt4 book ai didi

javascript - 未定义索引 : avatar

转载 作者:行者123 更新时间:2023-12-03 03:16:19 28 4
gpt4 key购买 nike

我有这段代码来上传头像。它工作正常,但如果我提交带有空头像的表单,我会得到 undefined index 头像。第一个代码是 php 代码,然后是 Html 代码,最后一个代码是文件输入代码。感谢各位 friend 的帮助。

    if(isset($_POST['submit'])){

$adminID = $_SESSION['adminID'];

if($_POST['avatar'] == ""){
$error[] = "Please Select a Picture!";
}

$type = explode('.', $_FILES['avatar']['name']);
$type = $type[count($type)-1];
$url = 'assets/images/users/'.$_SESSION['username'].'.'.$type;
if(in_array($type, array('gif', 'jpg', 'jpeg', 'png', 'JPG', 'GIF', 'JPEG', 'PNG'))) {
if(is_uploaded_file($_FILES['avatar']['tmp_name'])) {
if(move_uploaded_file($_FILES['avatar']['tmp_name'], $url)) {

try { //insert into database with a prepared statement
$stmt = $db->prepare("UPDATE admin SET avatar = '$url' WHERE adminID = $adminID");
$stmt->execute(array(
$adminID
));

echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
exit;
}
//else catch the exception and show the error.
catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}
}
}
?>

下面是文件输入的 HTML 代码,用户将用它来选择头像

    <div class="col-sm-4 text-center">
<?php
if(isset($error)){
foreach($error as $error){
echo '<p class="btn btn-warning">'.$error.'</p>';

}
}
?>
<input type="file" id="avatar" name="avatar" class="file" data-preview-file-type="any" />
</div>
<button type="submit" id="submit" name="submit" class="btn btn-success pull-right">Save <span class="fa fa-floppy-o fa-right"></span></button>

这是我的文件输入插件初始化代码

<script>
var btnCust = '<button type="button" class="btn btn-secondary" title="Add picture tags" ' +
'onclick="alert(\'Call your custom code here.\')">' +
'<i class="glyphicon glyphicon-tag"></i>' +
'</button>';
$("#avatar").fileinput({
overwriteInitial: true,
maxFileSize: 1500,
showClose: false,
showCaption: false,
showBrowse: false,
browseOnZoneClick: true,
removeLabel: '',
removeIcon: '<i class="fa fa-trash-o"></i>',
removeTitle: 'Cancel or Delete Selection',
elErrorContainer: '#kv-avatar-errors-2',
msgErrorClass: 'alert alert-block alert-danger',
defaultPreviewContent: '<img src="" alt=""><h6 class="text-muted">Click to select</h6>',
layoutTemplates: {main2: '{preview} ' + btnCust + ' {remove} {browse}'},
allowedFileExtensions: ["jpg", "png", "gif"]
});
</script>

最佳答案

您已将 avatar 字段作为 $_POST 数组的成员引用一次,然后又作为 $_FILES 数组的成员引用。

只需使用以下内容更改 if 条件即可消除错误并实现您想要执行的逻辑。

if($_FILES['avatar']['name'] == ""){
$error[] = "Please Select a Picture!";
}

关于javascript - 未定义索引 : avatar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758401/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com