Search code examples
angularangular-ngmodelng2-file-upload

How to get file name instead of path with ngModel and ng2-file-upload?


I need to get the file name of the input when is selected and save it to the database, but the only thing it seems to show is the fakepath of the file.

//component.html
<div class="col s12 file-field input-field" style="margin-left: -10px">
    <div>
        <input type="file" name="cat" [(ngModel)]="subf" ng2FileSelect [uploader]="uploader2"/>
    </div>
    <div class="file-path-wrapper" style="margin-right: -10px">
        <input class="file-path validate" name="banner" ngModel placeholder="Seleccione una Imagen" type="text">
        <label for="banner" style="margin-left: 10px">Banner</label>
    </div>
</div>

//component.ts
var subf: any;
console.log(subf);

The output I get is C:\fakepath\image.png and I only need image.png


Solution

  • you should have a button with a click event.

    <input style="display: none" type="file" (change)="onFileChanged($event)" #fileInput>
      <button type="button" (click)="fileInput.click()">Select File</button>
    

    and in the ts file

    onFileChanged(event) {
     console.log( event.target.files[0].name) );
     }