PHP progress bar

Asked

Viewed 1,542 times

2

I am 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 progress:

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

But what happens is that it only works on Opera and Chrome. Firefox and Safari do not work. The process of uploading the file, sending email and registering in a database works in any browser, even when the upload progress is displayed. I’m 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 Submit without filling in anything, the page marks the fields, because of the required and appears the full bar, in Firefox. But if I put to upload a file that same bar does not move:

inserir a descrição da imagem aqui

  • Any error in console in Safari?

  • No, not even in the firebug.

  • @Guilhermenascimento I put the form, thank you!

  • OK @Guilhermenascimento, I’ll wait for your edit. I added a comment in your reply too. Thanks for the help

2 answers

1

The required will not prevent you from triggering 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 from your file, but is from sending anything through the request.

In case you did it:

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

onclick cannot detect the required, because onclick detects clicks and not shoots of Forms. For this removes it.

The contents of uploaded files are sent via multi-part, so even if you do not send the file yet the request is sent, to avoid triggering the event you can simply use preventDefault onsubmit, something like (abridged 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 should go inside window.onload or $.ready, example I used $.ready even):

$.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 don’t have a Mac with Safari to test, but I believe the way I described works for all browsers.

  • In fact what happens, both in Safari and other browsers, besides Opera, is that the progress bar does not walk. But the file is sent normally, triggers the emails and writes to the server without problems. It’s only the perfume of progress that people are complaining...

  • its answer solved the problem of the load bar without any file, but I continue with the problem of the bar not loading the information while uploading the file, it is stopped....

  • I changed but now stopped even in Opera.... hehehe opened the DNS for external access, see: http://200.208.251.153/ptransfer

  • Sorry, I already added it. It’s giving firebug an error, I’m checking what it is. Thanks for while.

  • Yes, you can test.

  • Look @Guilherme, I’m not only "copying and cheating", I was trying to understand your excellent answer. I apologize if it seemed that I was waiting for the answer ready and paste the code. Anyway I will remake things with your answer. Thanks for now.

  • Yes @Guilherme, last night I made the changes as your answer, but for some reason it did not work in any browser plus progress. So I went back to the version I was and now I’m going to start testing again.

  • @Diego follows the HTML and JS: http://pastebin.com/raw/k8xDr0fN

Show 3 more comments

0

Use the library jQuery File Upload. They have a tutorial very nice of how to use the basics, but here’s my practical example:

    <!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.

  • Thank you for your reply, but I have not yet been able to make it work. I’ll try a little more to solve my script and if I don’t I’ll try to use this library.

  • 1

    It’s a good answer, but switching to jQuery doesn’t solve the problem of understanding how the pure DOM or Xmlhttprequest API works, meaning the answer can be useful for jQuery users, but for those who want to study the behavior or use other frameworks it doesn’t solve.

  • Fair. I thought the intention was to solve the problem. It seemed to me that he has this system in production, and precious hours go by in trying to manually develop things that are already stabilized in libraries and frameworks. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.