Mr.Gaja
Mr.Gaja

Reputation: 183

How to access type of uploaded file in angular 4?

I am trying to get the type of file uploaded in my angular component Here's my code html <input type="file" (change)="fileChange($event)" /> Typescript

fileChange(event) {                    
   console.log(event.target.files[0].type);
}

The above code logs file type correctly when I select any file except .doc files. When I select a doc file the type logged will be an empty string... Please help!!!

Upvotes: 1

Views: 10074

Answers (2)

Abhijith Darshan
Abhijith Darshan

Reputation: 161

Html

<input type="file" style="display: none;" id="fileInput" (change)="fileChange($event.target.files)">
<button (click)="selectFile()"> Select File </button>

TS

public selectedFile : File;

public selectFile() {
    document.getElementById("fileInput").click();
}

public fileChange(files: File[]) {
    if (files.length > 0) {
        this.selectedFile = files[0].type;
        console.log(this.selectedFile);
    }
}

For .doc it shows "application/msword".

For .docx it is application/vnd.openxmlformats-officedocument.wordprocessingml.document

Console.log Output

Upvotes: 3

tchelidze
tchelidze

Reputation: 8308

Alternative to file type, you get get file extension.

Try following

fileChange(event){ 
  console.log(event.target.files[0].name.split(".").pop());
}

Upvotes: 0

Related Questions