admin管理员组

文章数量:1406926

I am trying to get the type of file uploaded in my angular ponent 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!!!

I am trying to get the type of file uploaded in my angular ponent 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!!!

Share edited Jun 5, 2018 at 17:21 argoth 1,2639 silver badges16 bronze badges asked Jan 25, 2018 at 7:02 Mr.GajaMr.Gaja 1833 gold badges3 silver badges12 bronze badges 5
  • Does the empty string occur only when using angularjs? Cannot reproduce when not using angularjs – guest271314 Commented Jan 25, 2018 at 7:33
  • I tried only using angular... but why this happens only with doc files? other files like pdf , zip will work fine? – Mr.Gaja Commented Jan 25, 2018 at 7:35
  • Have not tried angularjs. Have you considered filing an issue with the authors and contributors to angularjs describing what you have experienced? – guest271314 Commented Jan 25, 2018 at 7:36
  • No.. Iam using angular 4 here – Mr.Gaja Commented Jan 25, 2018 at 7:38
  • Not familiar with the versions of angular. "application/msword" is set as type at File object at Chromium and Firefox when not using anguarjs. Can you create a plnkr plnkr.co to reproduce the issue? – guest271314 Commented Jan 25, 2018 at 7:42
Add a ment  | 

2 Answers 2

Reset to default 3

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

Alternative to file type, you get get file extension.

Try following

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

本文标签: javascriptHow to access type of uploaded file in angular 4Stack Overflow