繁体   English   中英

通过表单提交图像后生成成功还是错误消息?

[英]Making a success or error message after submitting image via form?

我真的是html和php的新手。 我正在尝试使用一个表单,该表单用于将图片上传到服务器。

<form class="myBtn" id="Upload" action="upload.php" method="post" enctype="multipart/form-data" style="visibility:hidden;"><br>
      Select template to upload:<br>
         <input type="file" name="fileToUpload" id="fileToUpload"><br>
         <input type="submit" value="Upload Image" name="submit">
</form>

这是我的HTML表单。

<?php $target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$needheight = 355;
$needwidth = 275;

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "Checked: File is an image! - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "Checked: File is not an image!";
        $uploadOk = 0;
    }
}

if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 1048576) {
  echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
if($imageFileType != "png") {
    echo "Sorry, only .PNG is allowed.";
    $uploadOk = 0;
}

if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
}

else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "Your cape template". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your template. Try again.";
    }
}

?>

在这里您可以看到我的PHP代码。 非常抱歉,它具有如此的WoC(代码墙),但是我真的不知道您需要帮助我的代码的哪些特定部分。

我使PHP工作了很长时间,但我做到了。 我可以成功将模板上传到服务器。 但是目前,成功提交模板后,我将重定向到另一个空白页面,其中显示:“已选中:文件是图像!-image / png!您的海角模板已上传!”

有没有一种方法不重定向到空白页,而是在主网站上直接显示成功或错误回显?

非常感谢您,我此刻陷入困境。

从表单中删除操作,以便页面将在同一页面上发布。 并防止您的html <form>从当前在upload.php php编写代码

<?php $target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$needheight = 355;
$needwidth = 275;

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "Checked: File is an image! - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "Checked: File is not an image!";
        $uploadOk = 0;
    }
}

if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 1048576) {
  echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
if($imageFileType != "png") {
    echo "Sorry, only .PNG is allowed.";
    $uploadOk = 0;
}

if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
}

else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "Your cape template". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your template. Try again.";
    }
}

?>

<form class="myBtn" id="Upload" action="" method="post" enctype="multipart/form-data" style="visibility:hidden;"><br>
      Select template to upload:<br>
         <input type="file" name="fileToUpload" id="fileToUpload"><br>
         <input type="submit" value="Upload Image" name="submit">
</form>

您可能可以执行以下操作-将所有代码保存在一页上,并在提交表单后显示相关消息。

<?php


    $errors=array();
    $allowed=array('png');
    $message = false;

    /* A utility function to report actual error ( if any ) */
    function uploaderror( $code ){ 
        switch( $code ) { 
            case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
            case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
            case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
            case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
            case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
            case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
            case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
            default: return "Unknown upload error";
        }
    }


    /* Only process this if these condition are met */
    if( isset( $_POST['submit'], $_FILES['fileToUpload'] ) ) {

        /* Obtain reference to upload - Object notation is quicker/easier imo */
        $obj=(object)$_FILES['fileToUpload'];
        $name=$obj->name;
        $tmp=$obj->tmp_name;
        $size=$obj->size;
        $type=$obj->type;
        $error=$obj->error;

        /* configuration */
        $target_dir = $_SERVER['DOCUMENT_ROOT']."/uploads/";
        $target_file = $target_dir . $name;
        $ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
        $needheight = 355;
        $needwidth = 275;




        if( $error == UPLOAD_ERR_OK && is_uploaded_file( $tmp ) ){
            /* Is it an image */
            $check = getimagesize( $tmp );
            if( !$check )$errors[]='Checked: File is not an image!';
            else{
                /* Find dimensions and other attributes */
                list( $width, $height, $type, $attr ) = $check;
                if( $width < $needwidth or $height < $needheight )$errors[]='Image is too small';
            }

            if( file_exists( $target_file ) )$errors[]='Sorry, that file already exists.';
            if( $size > 1048576 ) $errors[]='Sorry, your file is too large.';
            if( !in_array( $ext, $allowed ) ) $errors[]='Sorry, only images of type .'.strtoupper( implode( ', .',$allowed ) ).' '.(count($allowed)==1 ? 'is' : 'are').' allowed.';


            clearstatcache();


            if( empty( $errors ) ){
                $status = move_uploaded_file( $tmp, $target_file );
                $message = $status ? "Your cape template ". basename( $name ). " has been uploaded." : "Sorry, there was an error uploading your template. Try again.";
            }           

        } else {
            exit( uploaderror( $error ) );
        }
    }
?>
<!doctype html>
<html>
    <head>
        <title>File upload</title>
    </head>
    <body>
        <form class='myBtn' method='post' enctype='multipart/form-data'>
            Select template to upload:<br>
            <input type="file" name="fileToUpload" id="fileToUpload"><br>
            <input type="submit" value="Upload Image" name="submit">
        </form>
        <?php
            if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $message ) ){
                echo $message;
            }
            if( !empty( $errors ) ){
                foreach( $errors as $error ) echo $error . '<br />';
            }
        ?>
    </body>
</html>

很高兴您自己完成了PHP部分。 您已经使用了两个文件,一个用于HTML,另一个用于PHP,使其成为一个文件,并使用$ _SERVER ['PHP_SELF']。

<form class="myBtn" id="Upload" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"><br>
 <label>Select template to upload:</label><br>
     <input type="file" name="fileToUpload" id="fileToUpload"><br>
     <input type="submit" value="Upload Image" name="submit">
</form>

<?php 
$message = "";
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$target_dir = "/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$needheight = 355;
$needwidth = 275;
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo $message = "Checked: File is an image! - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo $message = "Checked: File is not an image!";
    $uploadOk = 0;
}
if (file_exists($target_file)) {
echo $message ="Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 1048576) {
echo $message ="Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "png") {
echo $message ="Sorry, only .PNG is allowed.";
$uploadOk = 0;
}

if ($uploadOk == 0) {
echo $message ="Sorry, your file was not uploaded.";
}

else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo $message ="Your cape template". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo $message ="Sorry, there was an error uploading your template. Try again.";
}
}
}
?>

<script>
var alert_msg = "<?php echo $message; ?>";
<?php if(strlen($message) > 1) { ?>
alert(alert_msg);
<?php } ?>
</script>

我使用警报来显示您的状态消息。 希望它能工作。

并请删除表单中的隐藏样式。(为什么会出现在其中)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM