我有此代碼來上傳頭像..它工作正常,但我得到未定義的索引頭像,如果我提交與空頭像的形式。第一個代碼是php代碼,然後是Html代碼,最後一個代碼是fileinput代碼。謝謝你幫助好朋友。未定義的索引:頭像
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>
,這裏是我的FileInput插件初始化代碼
<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>
代碼'if($ _ POST ['avatar'] ==「」)'有錯誤。 'avatar'字段屬於'$ _FILES'數組,而不是'$ _POST'數組。 – shahsani
需要他的form html來確定。請薩姆,補充一點。但它是一個刺的好地方。 – IncredibleHat
@Randall很抱歉,我遇到了一些網絡問題。謝謝,我現在添加了整個代碼。 –