Get all the information from the file that came from the input file

Asked

Viewed 1,708 times

3

I know it is possible in PHP to receive a certain file and get all the information from it, such as extension, size, date, among others.

I would like to know how it is possible to get this information with javascript.

The user needs to select an image, and would like to get the image extension, size and height.

  • What you’ve been trying to do?

  • Well I have achieved little in relation to that doubt. The only thing I’ve managed so far is to detect whether the input has been uploaded or not.

  • I continued with some information I saw on the internet, but I did not get a result. var Arq = this.files[0]; Alert(Arq.name);

2 answers

6


HTML5 provides a standard format for interaction with local files by specifying the File API (link in English). As an example of its features, the file API can be used to create a thumbnail view of the images when uploaded to the server or to allow the application to save a file reference when the user is offline. In addition, you can use client-side logic to confirm whether the mimetype of an upload matches your file extension or restrict the size of an upload.

The specification provides multiple interfaces to access files from a "local file system":

  • File - an individual file; provides legitimate information such as name, file size, mime type and a reference to the file identifier.
  • Filelist - a sequence similar to an array of File objects. (Think or dragging a file directory from the desktop).
  • Blob - Allows cutting a file in bytes ranges.

The most direct way to load a file is to use the default element . Javascript returns the list of selected File objects as a Filelist. This example uses the attribute "Multiple" to allow the selection of several files at once:

// Verifica se as APIs de arquivo são suportadas pelo navegador.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // Todas as APIs são suportadas!
} else {
  alert('A APIs de arquivos não é totalmente suportada neste navegador.');
}


function handleFileSelect(evt) {
  var files = evt.target.files; // Objeto FileList guarda todos os arquivos.
  var output = [];
  //Intera sobre os arquivos e lista esses objetos no output.
  for (var i = 0, f; f = files[i]; i++) {
//        console.log('Objeto do arquivo', f);
    // Informação adicional se for imagem:
    if (f.type.match('image.*')) {
      var reader = new FileReader();
      //A leitura do arquivo é assíncrona 
      reader.onload = (function(theFile) {
        return function(e) {
//              console.log('Img info', e, theFile);
          // Gera a miniatura:
          var img = document.createElement('img');
          img.src = e.target.result;
          img.title = escape(theFile.name);

          var span = document.createElement('span');
          //Obtém o tamanho:
          //Só é possível obter o tamanho do arquivo após o carregamento dele na miniatura, como o src é um base64 gerado à partir do arquivo local não terá custo de carregamento através da rede.
          img.onload = function(){
            var i = document.createElement('i');
          i.innerHTML = "<br>Tamanho Miniatura: " + img.width + "px Largura - " + img.height + "px Altura <br> Tamanho original:"+ img.naturalWidth+ "px Largura - " + img.naturalWidth+ "px Altura";
          span.appendChild(i);

          //Esse método retorna o tamanho calculado: Resultado esperado ((proporcional)x75) 

          //var width = img.clientWidth;
          //var height = img.clientHeight;
          }
          
          span.appendChild(img);
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }

    output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
      f.size, ' bytes,  última modificação: ',
      f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
      '</li>');
  }
  document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
img {
  height: 75px;
  border: 1px solid #000;
  margin: 10px 5px 0 0;
}
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

Source: https://www.html5rocks.com/pt/tutorials/file/dndfiles/

2

With the script below you can get the name, extension, size, height and width of the image sent by the user:

$('#imagem').change(function() {
  var img = document.getElementById('imagem');
  //Obter o nome da imagem
  var nome = this.files[0].name;
  //Obter a extensão
  var extensao = nome.replace(/^.*\./, '');

  //Calcular o tamanho do arquivo		
  var tamanho = ($("#imagem")[0].files[0].size / 1024);
  if (tamanho / 1024 > 1) {
    if (((tamanho / 1024) / 1024) > 1) {
      tamanho = (Math.round(((tamanho / 1024) / 1024) * 100) / 100);
      tamanho = tamanho + "Gb";
    } 
    else {
      tamanho = (Math.round((tamanho / 1024) * 100) / 100)
      tamanho = tamanho + "Mb";
    }
  } 
  else {
    tamanho = (Math.round(tamanho * 100) / 100)
    tamanho = tamanho + "kb";
  }
  //Obter largura e altura da imagem
  var altura = img.clientHeight;
  var largura = img.clientWidth;

  alert('Nome: ' + nome + "\nExtensão: " + extensao + '\nTamanho: ' + tamanho + "\nAltura: " + altura + "px" + "\nLargura: " + largura + "px");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<input type="file" name="imagem" id="imagem" accept="image/*">

Browser other questions tagged

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