Compares selected input file size with PHP disk_free_space

Asked

Viewed 31 times

0

I need a javascript script to compare the selected file sizes on input with the disk_free_space (in my case disk_free_space('D:')") of PHP, but it has to be before sending to the page that uploads, and detecting that it is larger than available, that blocks the button and shows a message, because I’m using the AJAX to send, I am using sending multiple files and I have available the JQuery.

<form id="formFiles" name="formFiles" action="javascript:void(0);" enctype="multipart/form-data">
  <input type="file" required name="arquivo[]" multiple="multiple">
  <button id="" type="submit">Enviar</button>
</form>

1 answer

1


You can do it. Just use element.files or $("input").prop("files"), with this you will have access to Metadata of the file (size, mimetype etc.).

Commented example:

/* Como o aqui não irá funcionar o código PHP, deixarei comentado */
//const MAX_FILESIZE = parseInt("<?php echo disk_free_space('D:'); ?>")

/* Exemplo do valor retornado no código anterior */
const MAX_FILESIZE = 2000000

$("input:file").change(function() {
  
  /* Reinicia o tamanho acumulado */
  let size = 0
  
  /* Captura o metada dos arquivos escolhidos e percorrer todos eles */
  Array.from($(this).prop("files")).map( file => {
    
    /* Soma o tamanho do arquivo em bytes com o tamanho acumulado */
    size += file.size
  })
  
  /**
   * Habilita o botão caso `size` seja menor que `MAX_FILESIZE`,
   * caso contrário desabilita
   */
  $("button:submit").prop("disabled", (size > MAX_FILESIZE))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formFiles" name="formFiles" action="javascript:void(0);" enctype="multipart/form-data">
  <input type="file" required name="arquivo[]" multiple="multiple">
  <button id="" type="submit">Enviar</button>
</form>

Browser other questions tagged

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