Home > Enterprise >  Limit Size and Type of an Uploaded File with Typescript
Limit Size and Type of an Uploaded File with Typescript

Time:09-22

forgive the beginner question, but I am trying to limit the size and type of an uploaded file via TypeScript.

My HTML currently looks like this:

      <label class="custom-file-upload">
        <input type="file" id="fileName" accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" onchange="validateFileType()"/>
          <i class="fas fa-cloud-upload"></i> 
          Upload
      </label>

While my TypeScript file looks like this:

  private validateFileType() {
    const fileName = (document.getElementById('fileName')as HTMLInputElement).value;
    const idxDot = fileName.lastIndexOf('.')   1;
    const extFile = fileName.substr(idxDot, fileName.length).toLowerCase();

    if (extFile === 'xls' || extFile === 'xlsx') {
        // TO DO
    } else {
        // Notification here
    }
  }

  private validateFileSize() {
    const fileName = (document.getElementById('fileName')as HTMLInputElement);

    // fileName.onchange = function() {
      if (fileName.files[0].size > 2097152) {
        // Notification here
        fileName.value = '';
      }
    };

Currently, it doesn't work, but I'm not sure why. Any help would be appreciated.

CodePudding user response:

Not a Vue.js expert here, but it seems to me that your event binding syntax is wrong.

Vue.js 2.x:

<input type="file" v-on:change="validateFileType"/>

Vue.js 3.x:

<input type="file" @change="validateFileType"/>
  • Related