Progress bar does not charge

Asked

Viewed 470 times

6

I have the code below, which feeds a progress bar while uploading the file.
What happens is the following: In some browsers, like Chrome and Opera, it works normally. Not in Firefox and Safari. There is something I could do in my code to be compatible with all browsers?

Charging function:

<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) {
    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>

HTML:

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

Save.php file

<?php
/* Arquivo: SalvarArquivo.php
 *
 * Este script salva o arquivo enviado e gera o link para envio por email.
 *
 * Dados de Origem: index.php
 *
 */

// Dados do banco
include "js/conn.php";

//Testa de o POST veio vazio, se sim volta para a página inicial
if (empty($_POST)) {
  ?><script>
  window.location.href = 'index.php';
  </script><?
  exit;
}

//Gera nome aleatório para cada arquivo
$tamanho = mt_rand(5,9);
$all_str = "abcdefghijlkmnopqrstuvxyzwABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$nome = "";
for ($i = 0;$i <= $tamanho;$i++){
   $nome .= $all_str[mt_rand(0,61)];
}

//Pega hora do click
$hora_inicial = $_POST['hora_inicio'];
//endereços de emails para envio e do remetente
$email_remetente = $_POST['email_remetente'];
$email_destinatario = $_POST['email_destinatario'];
$observacoes = utf8_encode($_POST['observacoes']);
if (empty($observacoes)) { $observacoes = utf8_encode('NÃO INFORMADAS'); }
//ip do cliente
$ip_envio = $_SERVER["REMOTE_ADDR"];
$tamanho = $_FILES['arquivo']['size'];  //em bytes

// Pasta onde o arquivo vai ser salvo
$_UP['pasta'] = 'BASE/';

// Tamanho máximo do arquivo (em Bytes)
$_UP['tamanho'] = 5147483648; // 5GB

// Array com as extensões permitidas
$_UP['extensoes'] = array('pdf', 'doc', 'xls', 'xlsx', 'docx', 'html', 'zip', 'rar', 'jpg', 'jpeg', 'png', 'iso', 'cdr', 'ppt', 'pptx', 'mp3', 'avi', 'mp4', 'mpeg', 'mpg', 'mov');

// Array com os tipos de erros de upload do PHP
$_UP['erros'][0] = 'Não houve erro';
$_UP['erros'][1] = 'O arquivo no upload é maior do que o limite do PHP';
$_UP['erros'][2] = 'O arquivo ultrapassa o limite de tamanho especifiado no HTML';
$_UP['erros'][3] = 'O upload do arquivo foi feito parcialmente';
$_UP['erros'][4] = 'Não foi feito o upload do arquivo';

// Verifica se houve algum erro com o upload. Se sim, exibe a mensagem do erro
if ($_FILES['arquivo']['error'] != 0) {
  die("Não foi possível fazer o upload, erro:
  " . $_UP['erros'][$_FILES['arquivo']['error']]);
exit; // Para a execução do script
}

// Caso script chegue a esse ponto, não houve erro com o upload e o PHP pode continuar

// Faz a verificação da extensão do arquivo
$extensao = @strtolower(end(explode('.', $_FILES['arquivo']['name'])));
if (array_search($extensao, $_UP['extensoes']) === false) {
            //extensão inválida
            ?>
              <html>
                <head>
                  <script src="sweet/dist/sweetalert.min.js"></script>
                  <link rel="stylesheet" type="text/css" href="sweet/dist/sweetalert.css">
                </head>
                <body>
                  <script>
                   sweetAlert({
                         title: "Erro!",
                         text: "Extensão <? print($extensao);?> não permitida!",
                         type: "error"
                      },
                      function () {
                        window.location.href = 'index.php';
                   });
                  </script>
                </body>
               </html>
            <?
            exit;
}

// Faz a verificação do tamanho do arquivo
else if ($_UP['tamanho'] < $_FILES['arquivo']['size']) {
            //tamanho maior que o permitido
            ?>
              <html>
                <head>
                  <script src="sweet/dist/sweetalert.min.js"></script>
                  <link rel="stylesheet" type="text/css" href="sweet/dist/sweetalert.css">
                </head>
                <body>
                  <script>
                   sweetAlert({
                         title: "Erro!",
                         text: "O arquivo enviado é muito grande, envie arquivos de até 5 GB.",
                         type: "error"
                      },
                      function () {
                        window.location.href = 'index.php';
                   });
                  </script>
                </body>
               </html>
            <?
}
// O arquivo passou em todas as verificações, hora de tentar movê-lo para a pasta
else {

//Grava o numero mais a extensão verificada no inicio do arquivo
$nome_final = $nome.'.'.$extensao;
// Mantém o nome original do arquivo
//$nome_final = $_FILES['arquivo']['name'];

// Depois verifica se é possível mover o arquivo para a pasta escolhida
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], $_UP['pasta'] . $nome_final)) {
// Upload efetuado com sucesso, exibe uma mensagem e um link para o arquivo

//link para o arquivo enviado
$server = "http://200.208.251.153/ptransfer/";
$anexo = $server.$_UP['pasta'].$nome_final;

include ("EnviarEmail.php");
//echo '<br><a href="'.$anexo.'">Baixar anexo</a>';

} else {

// Não foi possível fazer o upload, provavelmente a pasta está incorreta
echo "Não foi possível enviar o arquivo, tente novamente";
print_r(error_get_last());
}

}// FECHA ELSE VERIFICAÇÕES
?>
  • in the console of these browsers does not report any error message or depreciated method warning?

  • Nothing, no console shows anything, no error or warning

  • @Diego Upload works on firefox/opera, only Progress q does not?

  • Exactly, he uploads normally, but the staff complained that the "perfumery" of the Press bar does not appear in firefox/safari. Opera and non-mobile Chrome appears.

  • How are you decorating the component ? Put the CSS there

  • Actually it has no css, I’m only using the HTML5 progressbar and the question functions.

  • tried to use the <meter > instead of <progress>?

  • @Brumazzidb, using the meter nor appears on safari and FF

  • I’m having trouble checking, but does it have anything to do with event.loaded and event.position? Will the browers are using the same names?

Show 4 more comments

1 answer

4


Apparently you have to set the progressbar.max also for him to update.

In my tests it works like this in Chrome and Safari:

if (event.lengthComputable) {
    progressbar.max = event.total;
    progressbar.value = event.loaded;

jsFiddle: http://jsfiddle.net/dtgb309e/3/

  • Sergio, I’m going to test your answer on Monday. I can’t connect to the company to test it, okay? Thanks for the help, again :)

  • did not work, he continues not displaying the bar....

  • @Diego ok, which version of Safari? mobile or desktop? Can you play in my jsFiddle?

  • I managed to run your jsFiddle on both mobile and Firefox and Safari. I did a test and noticed that if I send the form without filling one of the required fields, it works. If I fill in all fields correctly, then it doesn’t work. I’m looking for what it can be. See here: http://200.208.251.153/ptransfer

  • @Diego when I test your code in the Safari tools event.lengthComputable is false. It makes me think you’re not setting the header Content-Length response. What code/language do you have on the server?

  • I edited the question, I put the part that receives the file...thanks for the help

  • @Good Diego. And who’s managing the traffic? Apache, Nginx?

  • It’s Apache, I’m using Wamp to work...

  • @Diego hard to figure out the problem without being able to test "from outside" the server. Test pass true in the xhr.open thus: request.open("POST", "SalvarArquivo.php", true);. Thus, sending in asynchronous mode may be that the browser gets free to receive server info. If it doesn’t work I think it’s a headers problem. Tell me if it worked when you can.

  • Good morning Sergio. Thanks for the tip. I tested it this way, but it still doesn’t work. About this headers problem, you say in the application, server or browser?

  • @Diego Hmmm... ok, in the case of the headers should be the browser seen to work with Chrome. I’ll keep thinking.

  • Thanks for all your help Sergio.

  • @Did Diego get anything else? Does this problem also happen in a local environment? (you can list steps to reproduce it). And by the way, you’ve tested libraries for that as this or any of the following: http://stackoverflow.com/a/10477249/2256325?

  • No Sergio, I will look for another method that meets this demand. In local environment the same error occurs. I found very interesting your libraries, I will try to migrate to some of them. I will mark your answer as certain, because it worked in "solo" test. Thank you!

  • @Diego, there’s one thing that puzzles me... is that when one of the camps wasn’t validated, the bar moved, right? If the problem also happens with wamp you can create a zip with the setup? so you can "have at home" and test. On your online server I can’t test.

  • Give me your email and I’ll send you the zip. That’s right, if I didn’t validate the field the bar walked...

Show 11 more comments

Browser other questions tagged

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