Validate Typescript file size

Asked

Viewed 323 times

0

I have to validate the file size, which cannot 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.

1 answer

1


I see no problem with your validation, but the 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!")
 }
  • Valeu worked out that way, it wasn’t working out for just that, it was in bytes not in megas.

Browser other questions tagged

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