PHP progress bar

2

I'm using the functions below to make a progress bar:

<script>
function upload() {
  var request = new XMLHttpRequest();
  request.upload.addEventListener("progress", uploadProgress, false);

  //envia o form
  var formData = new FormData();
  formData.append("file", document.getElementById('arquivo').files[0]);
  request.open("POST", "SalvarArquivo.php");
  request.send(formData);
}

function uploadProgress(event) {
  if (event.lengthComputable) {
    progressbar.max = event.total;
    progressbar.value = event.loaded;
   // var percent = Math.round(event.loaded * 100 / event.total); //cálculo simples de porcentagem.
   // document.getElementById('progressbar').value = percent; //atualiza o valor da progress bar.
  } else {
    document.getElementById('progressbar').value = 50; //atualiza o valor da progress bar.
  }
}
</script>

And a field to "show" the tempo:

<br>Andamento:<br><progress id="progressbar" value="0" max="100"></progress><br>

But what happens is that it works only on Opera and Chrome. In Firefox and Safari it does not work. The process of uploading the file, sending email and registering to a bank works on any browser, even displaying the progress of the upload. Am I doing something wrong?

FORM

         <form id="cadastro" name="cadastro" enctype="multipart/form-data" method="POST" action="SalvarArquivo.php" onsubmit="salvar.disabled = true; salvar.value='AGUARDE...'; return true;">
             <center><input type="email" name ="email_remetente" id="email_remetente" placeholder="Digite o seu email" maxlength = "50" required>
                     <input type="email" name ="email_destinatario" id="email_destinatario" placeholder="Digite o email do destinatário" maxlength = "50" required><br>
                     <textarea rows="1" cols="50" id="observacoes" name="observacoes" placeholder="Digite alguma observação, se houver." maxlength="50"></textarea><br>
                     <input type="hidden" id="hora_inicio" name="hora_inicio">
                     <input type="file" id="arquivo" name="arquivo" required>
                     <input type="button" id="animate-slide" value="Extensões permitidas" />
                     <p class="neat">
                        Extensões autorizadas: pdf, doc, xls, xlsx, docx, html, zip, rar, jpg, jpeg, png, iso, cdr, ppt, pptx, mp3, avi, mp4, mpeg, mpg, mov, wmv.<br>
                        <u>--> TAMANHO MÁXIMO PARA UPLOAD: 3GB. <--</u>
                     </p>
                     <br>Andamento:<br><progress id="progressbar" value="0" max="100"></progress><br>
                     <input type = "submit" id="salvar" name="salvar" onclick="javascript:upload();" value = "ENVIAR!" class="btn">

                    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
                    <!-- Peccin -->
                    <ins class="adsbygoogle"
                         style="display:block;background: transparent"
                         data-ad-client="ca-pub-6203353120448278"
                         data-ad-slot="1998794736"
                         data-ad-format="auto"></ins>
                    <script>
                    (adsbygoogle = window.adsbygoogle || []).push({});
                    </script>

             </center>
        </form>

UPDATE

If I click Send without filling anything, the page marks the fields, because of required and the full bar appears in Firefox. But if I put to file a file that same bar does not move:

    
asked by anonymous 22.11.2016 / 16:51

2 answers

1

required will not prevent you from firing the upload function depending on the way you wrote the script, the upload will process even if empty, this is because the upload progress is not yours file, but is sending anything through the request.

In case you did this:

<input type = "submit" id="salvar" name="salvar" onclick="javascript:upload();" value = "ENVIAR!" class="btn">

Onclick can not detect required , since onclick detects clicks and does not trigger forms. To do this remove it.

The contents of uploaded files are sent via multi-part, so even if you do not send the file, even if the request is sent, to avoid triggering the event you can simply use preventDefault inside onsubmit, something like ( short version):

<form id="cadastro" name="cadastro" enctype="multipart/form-data" method="POST" action="SalvarArquivo.php">

<input type="file" id="arquivo" name="arquivo" required>

<br>Andamento:<br><progress id="progressbar" value="0" max="100"></progress><br>
<input type="submit" id="salvar" name="salvar" value="ENVIAR!" class="btn">

</form>

And the javascript will look like this (this script must go inside window.onload or $.ready , example I used $.ready same):

$.ready(function() {
    document.getElementById("cadastro").addEventListener("submit", function (event)
    {
        event.preventDefault(); //Isto irá evitar o disparo prévio

        document.getElementById("cadastro").disabled = true;
        document.getElementById("salvar").disabled = true;

        //Se ocorrer algum erro de segurança ou qualquer outra coisa evita redirecionar
        setTimeout(upload, 1);

        return false;
    });
});

And within upload do this:

function upload()
{
  var request = new XMLHttpRequest();
  request.upload.addEventListener("progress", uploadProgress, false);

  request.onreadystatechange = function()
  {
      if (request.readyState == 4) {
        document.getElementById("cadastro").disabled = false;
        document.getElementById("salvar").disabled = false;
      }
  };

  //envia o form
  var formData = new FormData();
  formData.append("file", document.getElementById('arquivo').files[0]);
  request.open("POST", "SalvarArquivo.php");
  request.send(formData);
}

I do not have a Mac with Safari to test, but I believe the way I've described works for all browsers.

    
23.11.2016 / 17:12
0

Use the jQuery File Upload library. They have a tutorial pretty cool on how to use the basics, but here's my example practical:

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>jQuery File Upload Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    </head>
    <body>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="jquery.ui.widget.js"></script>
    <script src="jquery.iframe-transport.js"></script>
    <script src="jquery.fileupload.js"></script>
    <script>
$(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            $('#progressbar').css('display', 'block');
            $('#progressbar_span').html('');
            data.context = $("<span id='progressbar_span' class='label label-info'></span>").text('Carregando...').appendTo("#modal_gerenciar_arquivo_header");
            data.submit();
        },
        progressall: function (e, data) {
            $('#progressbar_msg').hide();
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progressbar .progress-bar').css(
                'width',
                progress + '%'
            );
        },
        done: function (e, data) {
            $('#progressbar_msg').show();
            $.each(data.result.files, function (index, file) {
                if(file.error != null){
                    $('#progressbar_msg').html('');
                    $('#progressbar_msg').html(
                        "<div class='alert alert-danger'>"+file.error+"</div>"
                    );
                } else {
                    $('#progressbar_msg').html('');
                }
            });
            $('#progressbar').css('display', 'none');
            data.context.text('Carregamento finalizado!');
        }
    });
});
</script>
<div class="progress" id="progressbar" style="display: none">
    <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%;">
        <span class="sr-only"></span>
    </div>
</div>
<p id="progressbar_msg"></p>
<input id="fileupload" type="file" name="files[]" data-url="script_de_upload.php">
</body> 
</html>

I use Bootstrap, but you can use any other CSS framework.

    
22.11.2016 / 17:30