Validate TypeScript file size

0

I have to validate the file size, which can not exceed 1024. How do I do this in TypeScript?

verificar(){
    debugger;
    let _this = this;
    document.getElementById("openModalVerificar").click();
    let formData: FormData = new FormData(),
    xhr: XMLHttpRequest = new XMLHttpRequest(),
    baseURL = Config.API;
    if(_this.file!=null && _this.file!=undefined && _this.file[0].size > 1024){
        for (let i = 0; i < _this.file.length; i++) {
            formData.append("file", _this.file[i], _this.file[i].name); 
        }
    } else {
        swal ("Tamanho não permitido!")
    }

but does not validate the file size.

    
asked by anonymous 11.12.2018 / 13:43

1 answer

1

I do not see a problem with your validation, but file[0].size returns the value in bytes, what would be the maximum size you would like? Let's assume it is at most 2MB (megabytes):

verificar(){
 debugger;
 let _this = this;
 // null e undefined retornam false para uma validação e conteúdo com valor retorn true, validação fica simplificada assim
 if(_this.file){
    // convertendo bytes para megas (1024 * 1024) e para o dobro (*2)
    if(_this.file[0].size <= 1024 * 1024 * 2) {
      for (let i = 0; i < _this.file.length; i++) {
        formData.append("file", _this.file[i], _this.file[i].name); 
      }
    } else {
      swal("Tamanho excedeu 2MB!")
    }

 } else {
    swal("Nenhum arquivo!")
 }
    
12.12.2018 / 14:28